是否有R函数可用于连续计数相同的值?

时间:2019-01-02 09:46:47

标签: r dataframe count row

我正在寻找一个函数,该函数可以通过以字符串为名称在新列中返回该数字,从而给出行中相同字符串的出现次数。让我们举个例子:

 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)
)

如果您有什么想法要发展,谢谢您的时间

1 个答案:

答案 0 :(得分: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)