从R中的方括号中提取数值

yptwkmov  于 2023-02-17  发布在  其他
关注(0)|答案(3)|浏览(169)

我在使用stringr包从方括号中提取数值时遇到了困难。
我有一个 Dataframe ,结构如下:

'data.frame':   18 obs. of  3 variables:
 $ participant: chr  "s07" "s08" "s10" "s11" ...
 $ position_1 : chr  "[-3.96002452]" "[-2.43317811]" "[0.57034622]" "[-2.93552563]" ...
 $ position_2 : chr  "[-6.40075519]" "[-2.26514695]" "[-0.98081968]" "[-2.91766826]" ...

现在,我想提取方括号内的数值,这样最后我就有了一个数据框,如下所示:

'data.frame':   18 obs. of  3 variables:
 $ participant: chr  "s07" "s08" "s10" "s11" ...
 $ position_1 : num -3.96002452 -2.43317811 0.57034622 -2.93552563 ...
 $ position_2 : num -6.40075519 -2.26514695 -0.98081968 -2.91766826 ...

我尝试使用stringr包,但未能成功地使语法工作。

mwkjh3gx

mwkjh3gx1#

使用gsub和适当的正则表达式,不需要附加包。

df[2:3] <- lapply(df[2:3], \(x) as.numeric(gsub('\\[|\\]', '', x)))
df
#   participant position_1 position_2
# 1         s07 -3.9600245 -6.4007552
# 2         s08 -2.4331781 -2.2651470
# 3         s10  0.5703462 -0.9808197
# 4         s11 -2.9355256 -2.9176683
  • 数据:*
df <- structure(list(participant = c("s07", "s08", "s10", "s11"), position_1 = c("[-3.96002452]", 
"[-2.43317811]", "[0.57034622]", "[-2.93552563]"), position_2 = c("[-6.40075519]", 
"[-2.26514695]", "[-0.98081968]", "[-2.91766826]")), class = "data.frame", row.names = c(NA, 
-4L))
zxlwwiss

zxlwwiss2#

使用readr包中的parse_number()

library(tidyverse)

# the data
participant <-c("s07", "s08", "s10", "s11")
position_1 <- c("[-3.96002452]", "[-2.43317811]" ,"[0.57034622]", "[-2.93552563]")
position_2 <- c("[-6.40075519]", "[-2.26514695]", "[-0.98081968]" ,"[-2.91766826]" )

df <- tibble(participant, position_1, position_2)

# the code
df %>% 
  mutate(across(-participant, ~parse_number(.)))
participant position_1 position_2
  <chr>            <dbl>      <dbl>
1 s07             -3.96      -6.40 
2 s08             -2.43      -2.27 
3 s10              0.570     -0.981
4 s11             -2.94      -2.92
hzbexzde

hzbexzde3#

example <- c("[-3.96002452]" ,"[-2.43317811]" ,"[0.57034622]", "[-2.93552563]")
readr::parse_number(example)

[1] -3.9600245 -2.4331781  0.5703462 -2.9355256

使用readr包(如果没有,请安装)。

相关问题