简体   繁体   English

匹配列表中不同长度的列的值(或行) r

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

I have a list with 3 columns我有一个包含 3 列的列表

A <- (1,2,3,4) 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) 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) 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.我需要将列与相同的名称保持在一起,但我需要将列 B 中的第 6 个值对齐(匹配)到列 A 和 C 的第二个值,然后将 B 中的第 12 个值对齐(匹配)到 A 和 C 中的第三个值,等等。 The data in between the desired values in col B can be thrown out.可以丢弃 col B 中所需值之间的数据。

I was looking at rowwise() to do this but I couldnt quite figure out how to write it.我正在查看 rowwise() 来执行此操作,但我无法弄清楚如何编写它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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