【问题标题】:How to add a name to a data frame and change a specific cell in R如何向数据框添加名称并更改 R 中的特定单元格
【发布时间】:2021-01-17 21:33:08
【问题描述】:

这是我的数据示例:

    class   gender
Yellow  12  F
Blue    14  M
red 13  F

我想为颜色添加一个名称,然后将“红色”更改为“紫色”

所以我会得到下表:

Colour  class   gender
Yellow  12  F
Blue    14  M
Purple  13  F

我使用了以下代码

setNames(cbind(rownames(df), df), 
          c("colour"))

但是,它不起作用。提前感谢您的帮助

【问题讨论】:

    标签: r dplyr data.table


    【解决方案1】:

    我们使用rownames_to_columnreplace 创建一个列,将“颜色”列中的“红色”值改为“紫色”

    library(dplyr)
    library(tibble)
    df1 <- df1 %>%
       rownames_to_column("Colour") %>%
       mutate(Colour = replace(Colour, Colour == "red", "Purple"))
    

    -输出

    df1
    #  Colour class gender
    #1 Yellow    12      F
    #2   Blue    14      M
    #3 Purple    13      F
    

    setNames 在 OP 的帖子中,需要“颜色”以及“df”的列名

    setNames(cbind(rownames(df), df), 
          c("Colour", names(df)))    
    

    数据

    df1 <- structure(list(class = c(12L, 14L, 13L), gender = c("F", "M", 
    "F")), class = "data.frame", row.names = c("Yellow", "Blue", 
    "red"))
    

    【讨论】:

    • SetNames 不会改变颜色(所以没意思,抱歉); dplyr 添加名称,但不改变颜色
    • @user330 我添加了我得到的输出,与您的预期输出相同
    • @user330 我没有关注您对dplyr 解决方案的评论。当我得到预期的输出时,你能澄清一下吗
    • 谢谢,是的,但在我的原始示例中,它不会改变颜色,
    • 感谢两位抽出宝贵时间。我都赞成,但我喜欢基本的 R 代码和 @akrun,我真的很抱歉。
    【解决方案2】:

    希望这个基本 R 选项对你有用

    cbind(
      Color = gsub("^red$", "Purple", row.names(df)),
      df, 
      row.names = NULL
    )
    

    给了

       Color class gender
    1 Yellow    12      F
    2   Blue    14      M
    3 Purple    13      F
    

    数据

    > dput(df)
    structure(list(class = c(12L, 14L, 13L), gender = c("F", "M", 
    "F")), class = "data.frame", row.names = c("Yellow", "Blue",
    "red"))
    

    【讨论】:

    • @akrun 是的,我现在看到了。对 OP 的 cmets 的支持很奇怪
    【解决方案3】:

    以防万一,data.table 解决方案:

    library(data.table)
    setDT(df, keep.rownames = TRUE)  # tranform df into a data.table a change the row names into a column called rn
    setnames(df, "rn", "Color")  # change the name
    df[Color=='red', Color:="purple"] # change "red" to "purple"
    df
    

    【讨论】:

    • 请注意,您可以将setDT(df, keep.rownames = TRUE)setnames(df, "rn", "Color") 都简化为setDT(df, keep.rownames = "Color")
    【解决方案4】:

    这是一个基本的 R 选项:

    #add rowname as new column
    df$Colour <- rownames(df)
    #remove rowname
    rownames(df) <- NULL
    #replace 'red' with 'Purple'
    df$Colour[df$Colour == 'red'] <- 'Purple'
    df
    
    #  class gender Colour
    #1    12      F Yellow
    #2    14      M   Blue
    #3    13      F Purple
    

    【讨论】:

      猜你喜欢
      • 2020-02-20
      • 2022-01-03
      • 2022-01-09
      • 1970-01-01
      • 2016-12-08
      • 2018-11-17
      • 2015-03-13
      • 1970-01-01
      • 2017-08-23
      相关资源
      最近更新 更多