Extracting data from a data frame in R

3

I have a date frame in R and the table has row sets with the same attribute (name of an instance) and with different columns with data about 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 do to extract only the values from instance 1 to one of the values in a vector, then the same thing for Instance 2?

You could use subset of the value and place the scope in brackets:

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

But the point is that I have 32 instances with 100 reps each and did not want to have to do the same 32-fold operation.

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

    
asked by anonymous 03.12.2018 / 16:00

1 answer

4

You can split data with the split function and then apply the columns 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)

Data.

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)
    
03.12.2018 / 17:45