且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

计算 R 中一组变量中值的出现次数(每行)

更新时间:2023-08-28 16:10:40

尝试

apply(df,MARGIN=1,table)

其中 df 是您的 data.frame.这将返回一个与 data.frame 中行数相同长度的列表.列表的每一项对应data.frame的一行(顺序相同),是一张表格,内容是出现次数,名称是对应的值.

Where df is your data.frame. This will return a list of the same length of the amount of rows in your data.frame. Each item of the list corresponds to a row of the data.frame (in the same order), and it is a table where the content is the number of occurrences and the names are the corresponding values.

例如:

df=data.frame(V1=c(10,20,10,20),V2=c(20,30,20,30),V3=c(20,10,20,10))
#create a data.frame containing some data
df #show the data.frame
  V1 V2 V3
1 10 20 20
2 20 30 10
3 10 20 20
4 20 30 10
apply(df,MARGIN=1,table) #apply the function table on each row (MARGIN=1)
[[1]]

10 20 
 1  2 

[[2]]

10 20 30 
 1  1  1 

[[3]]

10 20 
 1  2 

[[4]]

10 20 30 
 1  1  1 

#desired result