r - 如何通过提取将列拆分为两列?

我想将列分成两列,然后提取数字并将其单独保留在一列中。

df <- data.frame(V1 = c("[1] Strongly disagree", "[2] Somewhat disagree", "[3] Neither", "[4] Somewhat agree", "[5] Strongly agree"))
                  V1
 [1] Strongly disagree
 [2] Somewhat disagree
 [3] Neither
 [4] Somewhat agree
 [5] Strongly agree

我尝试使用 tidyr 中的 separate 函数:

tidyr::separate(df, V1, into = c("Value", "Label"), sep = "] ")

Value   Label
[1      Strongly disagree           
[2      Somewhat disagree           
[3      Neither         
[4      Somewhat agree          
[5      Strongly agree

我也许可以用另一个函数删除 [,但我想知道我是否可以一步解决这个问题,并想知道是否有另一个函数可以完成这项工作。

我想把这个弄到最后

        Label        Value
 Strongly disagree     1
 Somewhat disagree     2
 Neither               3
 Somewhat agree        4
 Strongly agree        5

最佳答案

如果您更喜欢 base R,这里是 base R 解决方案:

df <- data.frame(V1 = c("[1] Strongly disagree", "[2] Somewhat disagree", "[3] Neither", "[4] Somewhat agree", "[5] Strongly agree"))

df$value = as.numeric(regmatches(df$V1, regexpr(r"(\d)", df$V1)))

df$V1 = regmatches(df$V1, regexpr("(?<=] ).*", df$V1, perl=TRUE))
df
#>                  V1 value
#> 1 Strongly disagree     1
#> 2 Somewhat disagree     2
#> 3           Neither     3
#> 4    Somewhat agree     4
#> 5    Strongly agree     5

由 reprex package 创建于 2020-09-05 (v0.3.0)

regmatches是一个基本的 R 函数,它从向量中返回匹配的值,它以一个向量和一个 regexpr 作为输入。对象。

如果第一种情况(value列)\d用于提取数字。 在第二种情况下,(?<=] ).*用于返回在 ] 之后匹配的任何内容,

https://stackoverflow.com/questions/63745883/

相关文章:

python - 类型错误 : request() missing 1 required posit

python - 如何在 Python 中订阅 NATS 主题并继续接收消息?

python - 在列表字典中查找最大列表范围的更好(更简洁)方法是什么

r - separate_rows 在结果周围生成引号

html - 轮播滑动动画不适用于 Bootstrap 4.5.2

c - main的地址是什么?

vue.js - 将插槽从 Vue 2 迁移到 Vue 3

python - Python 中的日期字符串格式化

docker - 如何查看在我的 Google Cloud Platform Cloud Run 服

angular - 使用@input 对 Angular 组件进行单元测试