2016-11-04 283 views
0

我环顾四周寻找答案,并没有完全想出解决方案。如何在R数据框中将一列分成多列

我试图划分多个(〜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:我一直在用管道%>%,因此如果任何人有一个解决方案,我可以改造“计数” data.frame而无需创建一个新的data.frame,这将是膨胀!

PSS我怀疑哈德利的功能之一可能是我所需要的东西(如mutate_each?),但我一直没能弄明白..

+0

试试这个'计数%>%mutate_each(玩意儿(./小时),-Hours)' – agenis

+0

但你在那里ISN 'mutate_each'的帮助文件中只有一个例子 – agenis

+5

请不要发布像'rm(list = ls())'这样的代码,除非它对您的示例至关重要。这不是某种人想要复制/粘贴和意外运行的东西。 – Gregor

回答

2

我实在看不出有什么不对您基地R方式,它非常干净。如果您担心在不运行第一行的情况下多次意外运行第二行,请参考原始counts列如下。我会做微小的调整,像这样做:无论names长度

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

使用[[[保证数据类型。

我喜欢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) 
+0

op的答案+我的好的组合 – agenis

相关问题