Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R在数据帧的每一行中计算字符串变量_R_String_Dataframe - Fatal编程技术网

R在数据帧的每一行中计算字符串变量

R在数据帧的每一行中计算字符串变量,r,string,dataframe,R,String,Dataframe,我有一个类似这样的数据帧,其中每一行代表一个样本,并且有相同字符串的重复 > df V1 V2 V3 V4 V5 1 a a d d b 2 c a b d a 3 d b a a b 4 d d a b c 5 c a d c c 我希望能够创建一个新的数据帧,其中理想情况下,标题是前一个数据帧(a、b、c、d)中的字符串变量,每行的内容是每个数据帧中各个变量的出现次数 原始数据帧。使用上面的例子,这看起来像 > df2

我有一个类似这样的数据帧,其中每一行代表一个样本,并且有相同字符串的重复

> df
  V1 V2 V3 V4 V5
1  a  a  d  d  b
2  c  a  b  d  a
3  d  b  a  a  b
4  d  d  a  b  c
5  c  a  d  c  c
我希望能够创建一个新的数据帧,其中理想情况下,标题是前一个数据帧(a、b、c、d)中的字符串变量,每行的内容是每个数据帧中各个变量的出现次数 原始数据帧。使用上面的例子,这看起来像

> df2
   a  b  c  d 
1  2  1  0  2  
2  2  1  1  1  
3  2  1  0  1
4  1  1  1  2  
5  1  0  3  1  
在我的实际数据集中,有数百个变量和数千个样本,因此如果我能够自动从原始数据帧中提取名称,并将它们按字母顺序排列到新数据帧的标题中,那将是非常理想的

你可以试试

library(qdapTools)
mtabulate(as.data.frame(t(df)))

或使用
base R

Un1 <- sort(unique(unlist(df)))
t(apply(df ,1, function(x) table(factor(x, levels=Un1))))

Un1您可以
堆叠列,然后使用
表格

table(cbind(id = 1:nrow(mydf), 
            stack(lapply(mydf, as.character)))[c("id", "values")])
#    values
# id  a b c d
#   1 2 1 0 2
#   2 2 1 1 1
#   3 2 2 0 1
#   4 1 1 1 2
#   5 1 0 3 1
table(cbind(id = 1:nrow(mydf), 
            stack(lapply(mydf, as.character)))[c("id", "values")])
#    values
# id  a b c d
#   1 2 1 0 2
#   2 2 1 1 1
#   3 2 2 0 1
#   4 1 1 1 2
#   5 1 0 3 1