r中的数据帧转换
我有一个带有一串列的df。每行代表每次取样行程中看到的物种。我想将其转换为矩阵或数据帧,其中每列都是一个物种,每行都是一次采样旅行。我想用纯素函数将其转换为分析。 我基本上想要相反的结果 原始格式r中的数据帧转换,r,dataframe,vegan,R,Dataframe,Vegan,我有一个带有一串列的df。每行代表每次取样行程中看到的物种。我想将其转换为矩阵或数据帧,其中每列都是一个物种,每行都是一次采样旅行。我想用纯素函数将其转换为分析。 我基本上想要相反的结果 原始格式 data.frame(speciesname=c("a","b","c","a"),sample.id=c(1,1,2,3),count=c(10,1,5,2)) speciesname sample.id count 1 a 1 10 2
data.frame(speciesname=c("a","b","c","a"),sample.id=c(1,1,2,3),count=c(10,1,5,2))
speciesname sample.id count
1 a 1 10
2 b 1 1
3 c 2 5
4 a 3 2
我想将其转换为如下所示:
a b c
1 10 1 0
2 0 0 5
3 2 0 0
我不想用if语句做一些可怕的双for循环,但如果这是我必须做的…使用xtabs()
库(2);acast(df1,sample.id~speciesname,value.var='count',fill=0)
也可以用于感谢您。我永远不会找到那个函数。
xtabs(count ~ sample.id + speciesname, df)
# speciesname
# sample.id a b c
# 1 10 1 0
# 2 0 0 5
# 3 2 0 0