【问题标题】:How to divide one column into multiple columns in R dataframe如何在R数据框中将一列分成多列
【发布时间】:2017-03-18 20:55:10
【问题描述】:

我四处寻找答案,但还没有完全想出解决方案。

我正在尝试将我的数据框(物种计数)的多个(约 60)列除以数据框中的单个列(样本工作量单位)

我能够想出下面的解决方案 - 但它比我想要的更混乱。正如现在所写的那样,我可能会不小心将最后一行代码运行两次,并通过两次除法来弄乱我的值。

下面是一个简短的示例,我在其中演示了我使用的解决方案。有什么更清洁的建议吗?

#short data.frame with some count data
#Hours is the sampling effort


counts=data.frame(sp1=sample(1:10,10),sp2=sample(1:10,10),
         sp3=sample(1:10,10),sp4=sample(1:10,10),
         Hours=rnorm(10,4,1))


#get my 'species' names
names=colnames(counts)[1:4]

#This seems messy: and if I run the second line twice, I will screw up my values. I want to divide all 'sp' columns by the single 'Hours' column

rates=counts
rates[names]=rates[,names]/rates[,'Hours']

ps:我一直在使用 %>%,所以如果有人有一个解决方案,我可以只转换“count”data.frame 而无需创建新的 data.frame,那就太好了!

p.s.s 我怀疑 Hadley 的功能之一可能有我需要的东西(例如 mutate_each?),但我无法弄清楚..

【问题讨论】:

  • 试试这个counts %>% mutate_each(funs(./Hours), -Hours)
  • 但你是对的,mutate_each 的帮助文件中没有一个示例
  • 请不要发布像rm(list = ls()) 这样的代码,除非它对您的示例至关重要。这不是人们想要复制/粘贴和意外运行的那种东西。
  • @Gregor,好点——谢谢你的建议。我的习惯是把它放在一切重新开始

标签: r transform multiple-columns


【解决方案1】:

我真的看不出你的基本 R 方法有什么问题,它非常干净。如果您担心在没有运行第一行的情况下意外多次运行第二行,只需引用原始的counts 列,如下所示。我会做一些微小的调整来做到这一点:

rates = counts
rates[names] = counts[names] / counts[["Hours"]]

使用[[[ 可以保证数据类型与names 的长度无关。

我确实喜欢dplyr,但它似乎更混乱:

# This works if you want everything except the Hours column
rates = counts %>% mutate_each(funs(./Hours), vars = -Hours)

# This sort of works if you want to use the names vector
rates = counts %>% mutate_at(funs(./Hours), .cols = names)

【讨论】:

  • 操作的答案+我的很好的组合
猜你喜欢
  • 2017-03-29
  • 1970-01-01
  • 1970-01-01
  • 2015-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-27
相关资源
最近更新 更多