我有一个像这样的df由colname Var1
上的1列组成df <- read.table(text = "Var1
|12|24|22|1|4
|12|23|22|1|445
|12|22|22|1|4
|101|116
|101|116|116|174
|101|116|125|174
|101|116|150|174
|101|116|156
|101|116|156|174
|101|116|162", header = TRUE, stringsAsFactors = FALSE)
问题:
答案 0 :(得分:5)
DF <- read.table(text = "Var1
|12|24|22|1|4
|12|23|22|1|445
|12|22|22|1|4
|101|116
|101|116|116|174
|101|116|125|174
|101|116|150|174
|101|116|156
|101|116|156|174
|101|116|162", header = TRUE, stringsAsFactors = FALSE)
x <- strsplit(DF$Var1, "|", fixed = TRUE)
sum(unlist(x) == "22")
#[1] 4
sum(sapply(x, function(s) "22" %in% s))
#[1] 3
答案 1 :(得分:5)
您也可以使用|
作为列分隔符来读取数据集,然后所有操作都非常简单
df <- as.matrix(read.table(text = "|12|24|22|1|4
|12|23|22|1|445
|12|22|22|1|4
|101|116
|101|116|116|174
|101|116|125|174
|101|116|150|174
|101|116|156
|101|116|156|174
|101|116|162", fill = TRUE, sep = "|"))
sum(df == 22, na.rm = TRUE)
# [1] 4
(rowSums(df == 22, na.rm = TRUE) > 0) + 0
# [1] 1 1 1 0 0 0 0 0 0 0
sum(rowSums(df == 22, na.rm = TRUE) > 0)
# [1] 3
或者,您也可以将原始df
转换为data.table
并使用tstrsplit
函数
df <- read.table(text = "Var1
|12|24|22|1|4
|12|23|22|1|445
|12|22|22|1|4
|101|116
|101|116|116|174
|101|116|125|174
|101|116|150|174
|101|116|156
|101|116|156|174
|101|116|162", header = TRUE)
library(data.table)
DT <- setDT(df)[, tstrsplit(Var1, "|", fixed = TRUE)]
DT[, sum(.SD == 22, na.rm = TRUE)]
# [1] 4
DT[, sum(rowSums(.SD == 22, na.rm = TRUE) > 0)]
# [1] 3
答案 2 :(得分:2)
使用正则表达式很容易
sum(grepl("\\|22(\\||$)", df$Var1))
答案 3 :(得分:1)
请在下次发布一个可重复的示例。
您可以使用grepl的正则表达式执行此操作。使用df作为data.frame
length(df[grepl('|22|',df$Var, fixed=T),])
这将回答你的第二个问题,可以很容易地适应问题1。