我想知道是否可以更新满足我使用过滤器选择的某些条件的所有行的值
我试图从这里开始:
|Disaster | TVal | FVal|
|-------------|------|-----|
|Tornado | 0 | 0 |
|Fire | 0 | 0 |
|Fire Tornado | 0 | 0 |
到这里:
|Disaster | TVal | FVal|
|-------------|------|-----|
|Tornado | 1 | 0 |
|Fire | 0 | 1 |
|Fire Tornado | 0.5 | 0.5 |
我选择这样的行
foo %>% filter(grepl("TORNADO", Disaster))
答案 0 :(得分:0)
根据输出,base R
选项将分割灾难'按空白列,在unique
之后获取unlist
元素(' un1'),然后循环显示' un1' (sapply(..
)),使用grepl
从灾难中获取逻辑矢量'列,将输出除以输出的行和(addmargins
创建总和列)并将输出分配给' foo'
un1 <- unique(unlist(strsplit(foo$Disaster, "\\s+")))
m1 <- addmargins(sapply(un1, function(x) grepl(x, foo$Disaster)),2)
foo[2:3] <- m1[,1:2]/m1[,3]
foo
# Disaster TVal FVal
#1 Tornado 1.0 0.0
#2 Fire 0.0 1.0
#3 Fire Tornado 0.5 0.5
foo <- structure(list(Disaster = c("Tornado", "Fire", "Fire Tornado"
), TVal = c(0L, 0L, 0L), FVal = c(0L, 0L, 0L)), .Names = c("Disaster",
"TVal", "FVal"), class = "data.frame", row.names = c(NA, -3L))