【问题标题】:How to create new column that is named based on the value of another column in the same row? [duplicate]如何创建基于同一行中另一列的值命名的新列? [复制]
【发布时间】:2020-07-17 05:49:27
【问题描述】:

我希望添加一个根据同一行中字符串的值重命名的列。

例如,我如何创建一个新列来显示此表中 PlayerID 末尾的数字或文本?因此,我想要这个:

PlayerID           
Hank Aaron + 7      
Babe Ruth + 5       
Ted Williams + 2i   
Hank Aaron + Outfield
Lou Gehrig + FirstBase

变成这样:

PlayerID                 NewColumn 
Hank Aaron + 7            7 
Babe Ruth + 5             5 
Ted Williams + 2i         2i 
Hank Aaron + Outfield     Outfield 
Lou Gehrig + FirstBase    FirstBase

正如您在上面看到的,我需要将加号后面的所有内容都包含在新列中。加号后面的值有时是数字,有时是字符和数字,有时只是字符。 提前致谢!

【问题讨论】:

标签: r string dataframe


【解决方案1】:

您可以使用正则表达式来捕获加号 (+) 之后的所有内容:

df$newcol <- sub('.*\\+\\s*(.*)$', '\\1', df$PlayerID)
df$newcol
#[1] "7"         "5"         "2i"        "Outfield"  "FirstBase"

或者相反,在"+"之前删除所有内容,而不是捕获。

sub('.*\\+\\s*', '', df$PlayerID)

如果+ 之后只有一个单词,您也可以使用不带正则表达式的stringr::word 来获取最后一个单词。

stringr::word(df$PlayerID, -1)

数据

df <- structure(list(PlayerID = c("Hank Aaron + 7", "Babe Ruth + 5", 
"Ted Williams + 2i", "Hank Aaron + Outfield", "Lou Gehrig + FirstBase"
)), class = "data.frame", row.names = c(NA, -5L))

【讨论】:

  • Ronak,一如既往,你很棒。谢谢。
【解决方案2】:

如果PlayerID列中只有一个加号,则可以在base R中组合sapply和strsplit

df$NewColumn <- sapply(strsplit(df$PlayerID, split = " + ", fixed = TRUE), function(x) x[[2]])

df
#                 PlayerID NewColumn
# 1         Hank Aaron + 7         7
# 2          Babe Ruth + 5         5
# 3      Ted Williams + 2i        2i
# 4  Hank Aaron + Outfield  Outfield
# 5 Lou Gehrig + FirstBase FirstBase

【讨论】:

    【解决方案3】:

    这是tidyverse 的策略。

    library(tidyverse)
    
    PlayerID <- c(
    "Hank Aaron + 7",
    "Babe Ruth + 5",       
    "Ted Williams + 2i",  
    "Hank Aaron + Outfield",
    "Lou Gehrig + FirstBase"
    )
    
    df <- data.frame(PlayerID, stringsAsFactors = F)
    df %>% 
      separate(PlayerID,into = c('Player', 'a', 'newColumn'), fill = 'right') %>% 
      unite('Name',Player:a, remove = F, sep = ' ') %>% 
      select(-c(Player:a))
    #>           Name newColumn
    #> 1   Hank Aaron         7
    #> 2    Babe Ruth         5
    #> 3 Ted Williams         2i
    #> 4   Hank Aaron  Outfield
    #> 5   Lou Gehrig FirstBase
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-11
      • 2021-02-23
      • 2021-09-30
      • 2021-05-19
      • 1970-01-01
      • 2021-04-17
      相关资源
      最近更新 更多