【问题标题】:Subsetting, reordering, and assigning according to a variable with dplyr使用 dplyr 根据变量进行子集、重新排序和分配
【发布时间】:2017-11-22 16:38:21
【问题描述】:

我想知道根据 dplyr 哲学为数据框子集分配值的“推荐”方式是什么。这可能最好用一个例子来说明。假设我有一个数据框(名为df):

V1 V2
 a  1
 b  2
 c  3

V1"a" 时,我想将V2 的值更改为2,并在V1"c" 时更改为1。在 R 基础语言中,这通常由rownames 实现:

rownames(df) <- df$V1
df[c("a", "c"), ]$V2 <- c(2, 1)

经过一番搜索,我能想到的使用 dplyr 语言的最简洁的解决方案是

df <- df %>% 
  mutate(V2 = recode(V1, "a" = 2, "c" = 1) %>% 
       ifelse(V1 %in% c("a", "c"), ., V2))

但感觉很笨拙。我错过了什么吗?使用 dplyr 更改数据框部分值的最佳方法是什么?

【问题讨论】:

    标签: r dataframe dplyr


    【解决方案1】:

    我们可以使用case_when

    df2 <- df %>%
      mutate(V2 = case_when(
        V1 %in% "a"    ~ 2L,
        V1 %in% "c"    ~ 1L,
        TRUE           ~ V2
      ))
    df2
    #   V1 V2
    # 1  a  2
    # 2  b  2
    # 3  c  1
    

    数据

    df<- read.table(text = "V1 V2
     a  1
     b  2
     c  3",
                    header = TRUE, stringsAsFactors = FALSE)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多