[英]How to divide one column into multiple columns in R dataframe
我一直在寻找答案,但还没有提出解决方案。
我正在尝试将数据帧中的多(〜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,那就好了!
pss我怀疑Hadley的功能之一可能具有我需要的功能(例如mutate_each?),但是我无法弄清楚。
我真的看不到您的基本R方法有什么问题,这很干净。 如果您担心不小心多次运行第二行而不运行第一行,只需参考以下原始counts
列即可。 我将做一些细微的调整来做到这一点:
rates = counts
rates[names] = counts[names] / counts[["Hours"]]
使用[
和[[
保证数据类型,无论names
的长度如何。
我确实喜欢dplyr
,但是这样做似乎更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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.