简体   繁体   中英

Matching values(or rows) of columns with different lengths in a list r

I have a list with 3 columns

A <- (1,2,3,4)

B <- (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24)

C <-(1,2,3,4)

I need to keep the columns together with the same names but I need to line up(match) the 6th value in col B to the second value of Col A and C, then 12th value in B to the third value in A and C, and so on. The data in between the desired values in col B can be thrown out.

I was looking at rowwise() to do this but I couldnt quite figure out how to write it.

Here's my best guess at generalizing:

x = list(
  A = c(1,2,3,4),
  B = c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24),
  C = c(1,2,3,4)
)

len = lengths(x)
x[len > min(len)] = lapply(
  x[len > min(len)], 
  \(z) z[seq(to = length(z), length.out = min(len), by = length(z) / min(len))]
)
x
# $A
# [1] 1 2 3 4
# 
# $B
# [1]  6 12 18 24
# 
# $C
# [1] 1 2 3 4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM