我有两个变量a
和b
a b
vessel hot
parts
nest NA
best true
neat smooth
我想用b
a
中的空白
la$b[i1] <- ifelse(la$b[i1] == "",la$a[i1],la$b[i1])
但它不起作用
答案 0 :(得分:0)
我们可以使用data.table
。将'data.frame'转换为'data.table'(setDT(df1)
),在'i'(b==''
)中指定条件,并指定对应于TRUE值的'a'值'我'到'b'。它应该很快,因为我们正在分配。
library(data.able)
setDT(df1)[b=='', b:= a]
df1
# a b
#1: vessel hot
#2: parts parts
#3: nest NA
#4: best true
#5: neat smooth
或者我们可以base R
i1 <- df1$b=='' & !is.na(df1$b)
df1$b[i1] <- df1$a[i1]
df1 <- structure(list(a = c("vessel", "parts", "nest", "best", "neat"
), b = c("hot", "", NA, "true", "smooth")), .Names = c("a", "b"
), class = "data.frame", row.names = c(NA, -5L))
答案 1 :(得分:0)
而不是
# la$b[i1] <- ifelse(la$b[i1] == "",la$a[i1],la$b[i1])
# what is i1? it doesn't seem to have any obvious function here
......应该是:
la$b <- ifelse(la$b == "", la$a, la$b)
假设您要将b中的空格替换为a并且适用于所有空白
df <- structure(list(a = c("vessel", "parts", "nest", "best", "neat"
), b = c("hot", "parts", NA, "true", "smooth")), .Names = c("a",
"b"), row.names = c(NA, -5L), class = "data.frame")
df$b <- ifelse(df$b=="", df$a, df$b)
# or, with `with`: df$b <- with(df, ifelse(b=="",a,b))
# > df
# a b
# 1 vessel hot
# 2 parts parts
# 3 nest <NA>
# 4 best true
# 5 neat smooth