简体   繁体   English

使用列的内容在 R 中创建一个新列

[英]Use content of the column to create a new column in R

I have a data frame like that:我有一个这样的数据框:

V1
W_2
W_4
W_5
W_10

Numbers which come after the "_" I would like to insert in a new column我想在新列中插入“_”之后的数字

Result结果

V1 V2
W_2 2
W_4 4
W_5 5
W_10 10

We can use sub to remove everything before and including underscore ( _ )我们可以使用sub删除包括下划线( _ )之前的所有内容

transform(df, V2 = sub('.*_', '', V1))
#Also
#transform(df, V2 = sub('.*_(.*)', '\\1', V1))

#    V1 V2
#1  W_2  2
#2  W_4  4
#3  W_5  5
#4 W_10 10

If we want to extract a number always as shown in the example, we can use parse_number如果我们想始终如示例中所示提取数字,我们可以使用parse_number

library(dplyr)
df %>% mutate(V2 = readr::parse_number(V1))

data数据

df <- structure(list(V1 = c("W_2", "W_4", "W_5", "W_10")), 
      class = "data.frame", row.names = c(NA, -4L))

We can use我们可以用

library(dplyr)
library(stringr)
df %>%
    mutate(V2 = str_remove(V1, ".*_"))

data数据

df <- structure(list(V1 = c("W_2", "W_4", "W_5", "W_10")), 
  class = "data.frame", row.names = c(NA, -4L))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM