R在数据帧的每一行中计数字符串变量 [英] R counting strings variables in each row of a dataframe

查看:136
本文介绍了R在数据帧的每一行中计数字符串变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框看起来像这样,每行代表一个样本,并重复相同的字符串

I have a dataframe that looks something like this, where each row represents a samples, and has repeats of the the same strings

> 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),并且每行的内容将是原始数据帧中的
中每个变量的出现次数。使用上面的示例,这将像

I want to be able to create a new dataframe, where ideally the headers would be the string variables in the previous dataframe (a, b, c, d) and the contents of each row would be the number of occurrences of each the respective variable from the original dataframe. Using the example from above, this would look like

> 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  

在我的实际数据集中,有数百个变量和数千个样本,所以它将如果我可以自动从原始数据框中提取名称,并将其按字母顺序排列成新的数据框的标题,那么是理想的。

In my actual dataset, there are hundreds of variables, and thousands of samples, so it'd be ideal if I could automatically pull out the names from the original dataframe, and alphabetize them into the headers for the new dataframe.

推荐答案

您可以尝试

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

mtabulate(split(as.matrix(df), row(df)))

或使用 base R

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

这篇关于R在数据帧的每一行中计数字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆