Extracting data from a data frame in R

Asked

Viewed 175 times

2

I have a data frame in R and the table has row sets with the same attribute (name of an instance) and different columns with data on each instance.

INSTÂNCIA   VALOR 1    VALOR 2
Instancia 1  10          20    
Instância 1  34          45
Instância 1  21          43
...
Instância 2  33          24
Instância 2  55          67
Instância 2  65          24
...

How can I extract only the values from instance 1 to one of the values in a vector, then the same thing for Instance 2?

Could use value subset and put range between brackets:

subset(data$VALOR1[1:3])
subset(data$VALOR2[4:6])

But the point is I have 32 instances with 100 repetitions each and I didn’t want to have to do the same operation 32 times.

Is there any way to use one for loop for this and have in my repeat routine the creation of a vetor(i) that stores to each interaction the 100 values of each instance? Thus, after 32 iterations, 32 vectors would be generated, each with 100 values for each Instance.

1 answer

3

Can divide data with the function split and then apply column extraction to each sub-df.

sp <- split(data, data$INSTÂNCIA)
result <- lapply(seq_along(sp), function(i){
  sp[[i]][, i + 1]
})

names(result) <- names(sp)
result
#$`Instância 1`
#[1] 10 34 21
#
#$`Instância 2`
#[1] 24 67 24

rm(sp)

Dice.

data <- read.table(text = "
INSTÂNCIA   VALOR.1    VALOR.2
'Instância 1'  10          20    
'Instância 1'  34          45
'Instância 1'  21          43
'Instância 2'  33          24
'Instância 2'  55          67
'Instância 2'  65          24
", header = TRUE)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.