I want to perform a column-wise operation in R on column pairs. The function I actually want to use is not the one shown here, because it would complicate this example.
I have a dataframe:
df <- data.frame(p1 = c(-5, -4, 2, 0, -2, 1, 3, 4, 2, 7)
,p2 = c(0, 1, 2, 0, -2, 1, 3, 3, 2, 0))
and a vector of the same length as the df
:
tocompare <- c(0, 0, 2, 0, 2, 4, 16, 12, 6, 9)
I want to run a function that compares each column of df
to the tocompare
object. The steps I need to take is:
- Make a two-element list. First element is a two-column dataframe
x
, in which the first column comes from thedf
and the second column is thetocompare
object. Second element is a number. (this is needed for my actual function to work, I appreciate that it is not needed in this example). This number is constant for all iterations of this process (it's a number of rows indf
/ length oftocompare
) in this example, it's10
.
data1 <- list(x = cbind(df %>% select(1), tocompare), N = length(tocompare))
# select(1) is used rather than df[,1] ensures the column header is kept
- Compare the two columns of the first element (called
x
) of thedata1
list. The function that I use in real life is notcor
; this simplified example captures the problem. I wrotemy_function
in such a way that it needs thedata1
object created above.
my_function <- function(data1){
x <- data1[[1]]
cr <- cor(x[,1], x[,2])
header <- colnames(x)[1]
print(c(header, cr))
}
cr_df1 <- my_function(data1)
I can do the same for the second df
column:
data2 <- list(x = cbind(df %>% select(2), tocompare), N = length(tocompare))
cr_df2 <- my_function(data2)
And make a dataframe of final results:
final_df <- rbind(cr_df1, cr_df2) %>%
`rownames<-`(NULL) %>%
`colnames<-`(c("p", "R")) %>%
as.data.frame()
the output will look like this:
> final_df
p R
1 p1 0.7261224
2 p2 0.6233169
I would like to do this on a dataframe with thousands of columns. The bit I don't know is how to split the single dataframe into multiple two-column dataframes and then run my_function
on these many small dataframes to return a single output. I think I would be able to do it with a loop
and with transposing the df
, but maybe there is a better way (I feel I should try to use map
here)?
2条答案
按热度按时间mspsb9vt1#
您可以使用
map
来迭代地应用您的函数,而不是循环。要将 Dataframe 拆分为列,只需一次选择一列。1:ncol(df)
将生成列号序列。因此要使函数处理这些列,请首先将其更改为输出 Dataframe
然后使用
map
将其打包,但使用map_df
,以便每次迭代都作为一行绑定到 Dataframe并与
编辑:如果
map_df
调用中的函数花费的时间太长,而您希望使用furrr
对其进行并行化,则可以使用unguejic2#
更通用的方法是使用
split.default()
,然后将函数应用于列表的每个元素