M
M
makbuk2017-09-14 09:50:58
R
makbuk, 2017-09-14 09:50:58

R how to make a subset on several fields in a loop?

I have data

field1 field2    field3    field4 field5 field6 field7 field8
   text  text1 segment_1 31-Jan-13    2.7   0.21   1.44   1.29
   text  text1 segment_1 01-May-13    0.7   2.90   0.76   0.38
   text  text1 segment_1 31-Jul-13   -2.3  -0.95  -1.73  -1.95

The first three fields are a composite key, I need to sequentially make a subset of data based on a unique composite key.
If you do this in a loop over one field, everything works.
for (j in 1:length(unique(InputData[,3]))) {
  InputDataSubset <- InputData[InputData[,3] == unique(InputData[,3])[j],]
print(unique(InputData[,3])[j])  
print(InputDataSubset)  
}

But when I try it on multiple fields
for (j in 1:length(unique(InputData[,1:3]))) {
  InputDataSubset <- InputData[InputData[,1:3] == unique(InputData[,1:3])[j,],]
  print(unique(InputData[,3])[j])  
  print(InputDataSubset)  
}

I get an error

Error in Ops.data.frame(InputData[, 1:3], unique(InputData[, 1:3])[j, :
'==' only defined for equally-sized data frames

How can such a problem be solved?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
makbuk, 2017-09-14
@makbuk

I found a solution, if anyone knows a better option please let me know.

InputDataSubset<-by(InputData, InputData[, colnames(InputData)[1:3]], FUN=function(df) df)

for (j in 1:length(InputDataSubset)) {
    print(InputDataSubset[j])
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question