我有这样的df:
v1
a.1
b.3
cz.90
如何创建一个新列,等于:
v1 v2
a.1 1
b.1 3
cz.90 90
在“。”之后。我的数字可能从1一直到999,所以无法根据特定位置进行操作
答案 0 :(得分:2)
您需要使用.
作为分隔符来分割字符串
library(stringr)
# this will create a 2 columns matrix, first column: what comes before .
# second column what comes after
# number of rows = number of rows in df
split_matrix <- str_split_fixed(df$v1,fixed("."),2)
# assign the second column from split_matrix to df$v2
df$v2 <- as.numeric(split_matrix[, 2])
df
# v1 v2
#1 a.1 1
#2 b.3 3
#3 cz.90 90
由于您的问题中包含tidyverse
标签,因此可以进行编辑:
df%>% mutate(v2=as.numeric(str_split_fixed(df$v1,fixed("."),2)[,2]))
答案 1 :(得分:1)
使用带有sub
的正则表达式,您可以执行以下操作:
library(dplyr)
df %>% mutate(New = as.numeric(sub(".*\\.","",v1)))
v1 New
1 a.1 1
2 b.3 3
3 cz.90 90