[英]Ratio of elements of vectors, in a list of vectors
I have a data frame which has a column: 我有一个带有列的数据框:
> head(df$lengths,5)
[[1]]
[1] "28"
[[2]]
[1] "33"
[[3]]
[1] "47" "37" "42" "41"
[[4]]
[1] "41" "39" "64" "54"
[[5]]
[1] "45" "22" "23"
I would like to operate on the elements in the vectors, to obtain the ratios of the element(i) to the element(ik) in each vector. 我想对向量中的元素进行运算,以获得每个向量中element(i)与element(ik)的比率。 Where a ratio cannot be obtained because element(ik) has invalid index, the result should be NA.
如果由于element(ik)的索引无效而无法获得比率,则结果应为NA。 The desired output is like this, where I specified k=1:
所需的输出是这样的,其中我指定了k = 1:
[[1]]
[1] NA
[[2]]
[1] NA
[[3]]
[1] NA (37/47) (42/37) (41/42)
[[4]]
[1] NA (39/41) (64/39) (54/64)
[[5]]
[1] NA (22/45) (23/22)
as for k=2: 至于k = 2:
[[1]]
[1] NA
[[2]]
[1] NA
[[3]]
[1] NA NA (42/47) (41/37)
[[4]]
[1] NA NA (64/41) (54/39)
[[5]]
[1] NA NA (23/45)
I have little clue on how to approach this, I would think to perform some loops, but in R, it seems complicated. 我对如何实现这一点几乎一无所知,我想执行一些循环,但是在R中,它似乎很复杂。 Please advice.
请指教。
We loop through the list
elements ( lapply(..
), if
the length
of the list
element is 1, we return 'NA' or else
divide the next value by the current value and concatenate with NA
. We convert to numeric
as the original list
elements were character
class. 我们遍历
list
元素( lapply(..
), if
list
元素的length
为1,则返回'NA', else
将下一个值除以当前值,并与NA
串联。我们将其转换为numeric
作为原始值list
元素是character
类。
lapply(df$lengths, function(x) if(length(x)==1) NA
else c(NA, as.numeric(x[-1])/as.numeric(x[-length(x)])))
We could use the lag/lead
function in dplyr/data.table
for k values greater than 1. 对于大于1的k值,我们可以在
dplyr/data.table
使用lag/lead
函数。
library(dplyr)
k <- 2
lapply(df$lengths, function(x) {x <- as.numeric(x)
if(length(x)==1) NA
else c(rep(NA,k), na.omit(lead(x,k)))/na.omit(lag(x,k))})
#[[1]]
#[1] NA
#[[2]]
#[1] NA
#[[3]]
#[1] NA NA 0.893617 1.108108
#[[4]]
#[1] NA NA 1.560976 1.384615
#[[5]]
#[1] NA NA 0.5111111
Or without using any packages, we can do with head/tail
functions 或不使用任何包装,我们可以使用
head/tail
功能
lapply(lst, function(x) {x <- as.numeric(x)
if(length(x)==1) NA
else c(rep(NA, k), tail(x, -k)/head(x,-k))})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.