【问题标题】:Create a new dataframe column with the first element of elements in another column in R [duplicate]使用R中另一列中元素的第一个元素创建一个新的数据框列[重复]
【发布时间】:2018-10-07 10:21:41
【问题描述】:

我想在我的数据框中创建一个新列,以便它由同一数据框中另一列中的第一个元素(或两个元素)组成。例如

   columnA
1   "1234"
2   "9876"
3   "4567"

变成:

   columnA    columnB
1   "1234"       "12"
2   "9876"       "98"
3   "4567"       "45"

我尝试使用这样的 dplyr 库:

dataframe %>%
    mutate( columnB = columnA[1:2] )

但这是试图检索前两行。

如果有人知道如何快速执行此操作(最好使用 dplyr 库),我将不胜感激。提前致谢。

【问题讨论】:

    标签: r dataframe


    【解决方案1】:
    df <- data.frame(columnA=c("1234","9876","4567"))
    df$columnB <- substr(df$columnA,1,2)           
     #   columnA columnB
     # 1    1234      12
     # 2    9876      98
     # 3    4567      45 
    

    如果你想使用dplyr:

    df <- df %>% mutate(columnB = substr(columnA,1,2))
    

    【讨论】:

    • 感谢您的快速响应。它运行良好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 2016-09-11
    相关资源
    最近更新 更多