仅从其他列创建列文本

GK8*_*K89 1 string replace r

我在R中有一个包含字母和数字的列的数据框.字母和数字的数量各不相同,因此解析将非常困难.我想要做的只是创建一个列,其中只包含包含字母和数字的列中的字母.典型的观察结果看起来像ABS98或GD798.

谢谢

Rei*_*son 5

一种方法是使用正则表达式gsub().使用类似您的数据:

df <- data.frame(Ind = rep(c("ABS98","GD798"), each = 5), Dat = rnorm(10))
Run Code Online (Sandbox Code Playgroud)

一个可能的正则表达式是:

with(df, gsub("[[:digit:]]", "", Ind))
Run Code Online (Sandbox Code Playgroud)

where "[[:digit:]]"匹配您的语言环境中的数字的任何传递,并用空字符串替换这些位"".这给了我们:

> with(df, gsub("[[:digit:]]", "", Ind))
 [1] "ABS" "ABS" "ABS" "ABS" "ABS" "GD"  "GD"  "GD"  "GD"  "GD"
Run Code Online (Sandbox Code Playgroud)

要将其添加为列,请覆盖Ind:

df2 <- transform(df, Ind = gsub("[[:digit:]]", "", Ind))

> head(df2)
  Ind        Dat
1 ABS  0.3685773
2 ABS  0.1186962
3 ABS -0.1049685
4 ABS -0.2448743
5 ABS -0.1896105
6  GD  0.8206612
Run Code Online (Sandbox Code Playgroud)

或添加一个新的

df3 <- transform(df, Ind2 = gsub("[[:digit:]]", "", Ind))

> head(df3)
    Ind        Dat Ind2
1 ABS98  0.3685773  ABS
2 ABS98  0.1186962  ABS
3 ABS98 -0.1049685  ABS
4 ABS98 -0.2448743  ABS
5 ABS98 -0.1896105  ABS
6 GD798  0.8206612   GD
Run Code Online (Sandbox Code Playgroud)

取决于哪种情况最适合您的用例.