首页 文章

使用条件将列变为单独的数据框

提问于
浏览
0

我想使用条件在mutate的管道末尾添加新列 into another data frame . 如果变量的长度为零,则在列中添加短划线,否则添加内容 . 这是我绑定结果数据帧的循环的一部分,因此所有列表只有一个项目,这里的数据帧只有一行 .

是否可以使用mutate将列添加到除管道中使用的数据框之外的数据框中?

我尝试使用我在这里找到的提示来解决这个问题:Combine mutate with conditional values

示例代码:

x <- "bbb"
y <- ""
end <- data.frame(a_col="aaa")

end <- x %>%
mutate (end, x_col = case_when(length()==0 ~ '-',
                         length()!=0 ~ .))

end <- y %>%
mutate (end, y_col = case_when(length()==0 ~ '-',
                         length()!=0 ~ .))

有了这两个,我明白了:"Error in UseMethod(" mutate_ ") : no applicable method for 'mutate_' applied to an object of class " character“”

“结束”数据框的预期结果:

a_col  x_col  y_col
1    aaa    bbb     -

1 回答

  • 1

    这是你要找的行为吗?

    x <- "bbb"
    y <- ""
    end <- data.frame(a_col = "aaa")
    
    end %>% mutate(x_col = case_when(nchar(x) == 0 ~ "-",
                                     TRUE ~ x),
                   y_col = case_when(nchar(y) == 0 ~ "-",
                                     TRUE ~ y))
    
      a_col x_col y_col
    1   aaa   bbb     -
    

    我想您要使用 ?nchar() 而不是 ?length() ,因此您将返回字符串中的字符数,而不是向量中的元素数 .

    你得到的错误是因为你试图调用 mutate(data = "bbb") ,但 mutate 要求 data 参数为 data.frame 或至少从 data.frame 继承其类 . 所以当你试图传递它时,它会抱怨 character .

    这是在列表中捕获多个管道结果的另一种方法,它们在将新列绑定到现有数据帧之前执行空字符串替换 .

    pipe_results <- list()
    
    pipe_results[["x"]] <- x # these names become column names
    pipe_results[["y"]] <- y
    
    map_dfc(pipe_results,
            ~ gsub("^$", "-", .)) %>%
                bind_cols(end, .)
    

相关问题