Tengo un marco de datos con las siguientes columnas:

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

Cómo leer el df1 que solo almacena un valor para los casos donde tenemos y = 1 para B [x, y]. Lo que significa:

Salida del marco de datos deseado 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))
0
shome 16 feb. 2020 a las 11:23

2 respuestas

La mejor respuesta

Utilizando mi respuesta de la publicación anterior, podemos obtener datos en columnas separadas B y D usando extract y luego filter para seleccionar dónde 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

datos

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))
1
Ronak Shah 16 feb. 2020 a las 08:43

Podemos hacer esto con parse_number después de 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

O otra opción es 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

Datos

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))
0
akrun 16 feb. 2020 a las 17:27