是否有R函数用于计算行中的相同值?

问题描述 投票:0回答:1

我正在寻找一个函数,它可以通过在一个新列中返回此数字并将此字符串作为名称返回给出一行相同字符串的次数。我们来举个例子:

 df <- data.frame(
   Year = rnorm(3), 
   hour = rnorm(3), 
   LOT = rnorm(3), 
   S123_AA = c('ABF4576','AG4633','AWW07954'), 
   S135_AA = c('ABF5403','ABF4576','A64ED56'), 
   S1763_BB = c('BF50343','BGF4761','B76WW56'),  
   S173_BB = c('BF50343','BDZ4641','B917656') 
 )

所以,在第一行,我们观察了两次`BF50343,我正在寻找构建新列以获得:

 df <- data.frame(
   Year = rnorm(3), 
   hour = rnorm(3), 
   LOT = rnorm(3), 
   S123_AA = c('ABF4576','AG4633','AWW07954'), 
   S135_AA = c('ABF5403','ABF4576','A64ED56'), 
   S1763_BB = c('BF50343','BGF4761','B76WW56'),  
   S173_BB = c('BF50343','BDZ4641','B917656'),
   ABF4576 = c(1,1,0),
   AG4633 = c(0,1,0),
   AWW07954 = c(0,0,1),
   ABF5403 = c(1,0,0),
   A64ED56 = c(0,0,1),
   BF50343 = c(2,0,0),
   BGF4761 = c(0,1,0),
   B76WW56 = c(0,0,1),
   BDZ4641 = c(0,1,0),
   B917656 = c(0,0,1)
)

如果您有任何想法,请感谢您的时间

r dataframe count row
1个回答
1
投票

您可以使用lapply循环遍历字符变量的唯一值:

cols <- !(colnames(df) %in% c("Year", "hour", "LOT")) ## variables of interest
vals <- as.character(unique(unlist(df[cols]))) ## unique values
res <- do.call("cbind", lapply(vals, function(x) rowSums(df[cols] == x)))
colnames(res) <- vals
df <- cbind(df, res)
© www.soinside.com 2019 - 2024. All rights reserved.