问题
I have a data frame with the following columns :
df <- A B C
heart_rate ['53.0', '1'] 94
heart_rate ['54.0', '2'] 1
heart_rate ['54.0', '1'] 9
heart_rate ['55.0', '0'] 1
heart_rate ['55.0', '1'] 7
How to read the df1 which just stores one value for cases where we have y= 1 for B[x,y].Which means :
Output desired dataframe df1
df1
A B C
heart_rate 53.0 94
heart_rate 54.0 9
heart_rate 55.0 7
structure(list(source = structure(c(1L, 1L, 1L), .Label = "heart_rate", class = "factor"),
values = structure(3:1, .Label = c("['171.0', '1']", "['172.0', '1']",
"['173.0', '0']"), class = "factor"), timediff = c(6L, 7L,
10L)), class = "data.frame", row.names = c(NA, -3L))
回答1:
Using my answer from the previous post, we can get data into separate columns B
and D
using extract
and then use filter
to select where D = 1
.
tidyr::extract(df, B, into = c('B', 'D'), "(\\d+\\.\\d+).*(\\d)") %>%
dplyr::filter(D == 1) %>%
dplyr::select(-D)
# A B C
#1 heart_rate 53.0 94
#2 heart_rate 54.0 9
#3 heart_rate 55.0 7
data
df <- structure(list(A = structure(c(1L, 1L, 1L, 1L, 1L),
.Label = "heart_rate", class = "factor"),
B = structure(c(1L, 3L, 2L, 4L, 5L), .Label = c("[53.0, 1]",
"[54.0, 1]", "[54.0, 2]", "[55.0, 0]", "[55.0, 1]"), class = "factor"),
C = c(94L, 1L, 9L, 1L, 7L)), class = "data.frame", row.names = c(NA, -5L))
回答2:
We can do this with parse_number
after filter
ing
library(dplyr)
library(stringr)
df %>%
filter(str_detect(B, "1\\]")) %>%
mutate(B = readr::parse_number(as.character(B)))
# A B C
#1 heart_rate 53 94
#2 heart_rate 54 9
#3 heart_rate 55 7
Or another option is base R
transform(subset(cbind(df, read.csv(text = gsub("[][ ]", "",
df$B), header = FALSE)), V2 == 1), B = V1)[names(df)]
# A B C
#1 heart_rate 53 94
#3 heart_rate 54 9
#5 heart_rate 55 7
data
df <- structure(list(A = structure(c(1L, 1L, 1L, 1L, 1L),
.Label = "heart_rate", class = "factor"),
B = structure(c(1L, 3L, 2L, 4L, 5L), .Label = c("[53.0, 1]",
"[54.0, 1]", "[54.0, 2]", "[55.0, 0]", "[55.0, 1]"), class = "factor"),
C = c(94L, 1L, 9L, 1L, 7L)), class = "data.frame", row.names = c(NA, -5L))
来源:https://stackoverflow.com/questions/60246707/how-to-extract-particular-values-from-a-factor-store-as-column-value-in-datafram