Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.0k views
in Technique[技术] by (71.8m points)

list - R: check multiple data.frame based on duplicated rows and re-organize data

mydata <- structure(list(X1 = c(1, 1, 1, 1, 1, 1), X2 = c(1, 4, 4, 3, 2, 
2), X3 = c(1, 2, 2, 3, 3, 3), X1 = c(-1, 1, 1, 1, -1, -1), X2 = c(1, 
-1, -1, 1, -1, -1), X3 = c(1, -1, 1, 1, -1, -1)), class = "data.frame", row.names = c(NA, 
-6L))

values <- data.frame(rbind(c(1, -3),
                           c(-99, 20),
                           c(1, 0),
                           c(0, 0),
                           c(-9, 0.3),
                           c(-99, 11)))

I have 2 data.frames, mydata, and values. Both data.frames have 6 rows. First I want to identify unique rows in mydata.

> mydata
  X1 X2 X3 X1 X2 X3
1  1  1  1 -1  1  1
2  1  4  2  1 -1 -1
3  1  4  2  1 -1  1
4  1  3  3  1  1  1
5  1  2  3 -1 -1 -1
6  1  2  3 -1 -1 -1

There are 5 unique groups:

#1 1 1 1 -1 1 1

#2 1 4 2 1 -1 -1

#3 1 4 2 1 -1 1

#4 1 3 3 1 1 1

#5 1 2 3 -1 -1 -1

For each of these 5 groups, I want to make a new list of length 5, one per unique group and store the corresponding rows from values.

> values
   X1   X2
1   1 -3.0
2 -99 20.0
3   1  0.0
4   0  0.0
5  -9  0.3
6 -99 11.0

So the resulting list might look like:

> mylist
[[1]]
[1] 1 -3.0

[[2]]
[1] -99 20.0

[[3]]
[1] 1  0.0

[[4]]
[1] 0  0.0

[[5]]
     X1     X2
1    -9    0.3
2   -99   11.0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can paste the values row-wise and find out unique groups which can be used to split the rows of values.

val <- do.call(paste, c(mydata, sep = '-'))
group <- match(val, unique(val))
split(values, group)

#$`1`
#  X1 X2
#1  1 -3

#$`2`
#   X1 X2
#2 -99 20

#$`3`
#  X1 X2
#3  1  0

#$`4`
#  X1 X2
#4  0  0

#$`5`
#   X1   X2
#5  -9  0.3
#6 -99 11.0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...