R对特定数据框列的Apply()函数 [英] R Apply() function on specific dataframe columns

查看:444
本文介绍了R对特定数据框列的Apply()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在数据框上使用apply函数,但只将函数应用于最后5列.

I want to use the apply function on a dataframe, but only apply the function to the last 5 columns.

B<- by(wifi,(wifi$Room),FUN=function(y){apply(y, 2, A)})

这会将A应用于y的所有列

This applies A to all the columns of y

B<- by(wifi,(wifi$Room),FUN=function(y){apply(y[4:9], 2, A)})

这仅将A应用于y的第4-9列,但B的总收益去除了前3列...我仍然想要那些,我只是不想将A应用于它们.

This applies A only to columns 4-9 of y, but the total return of B strips off the first 3 columns... I still want those, I just don't want A applied to them.

wifi[,1:3]+B 

也没有按照我的期望/要求做.

also does not do what I expected/wanted.

推荐答案

使用示例data.frame和示例函数(对所有值仅+1)

Using an example data.frame and example function (just +1 to all values)

A <- function(x) x + 1
wifi <- data.frame(replicate(9,1:4))
wifi

#  X1 X2 X3 X4 X5 X6 X7 X8 X9
#1  1  1  1  1  1  1  1  1  1
#2  2  2  2  2  2  2  2  2  2
#3  3  3  3  3  3  3  3  3  3
#4  4  4  4  4  4  4  4  4  4

data.frame(wifi[1:3], apply(wifi[4:9],2, A) )
#or
cbind(wifi[1:3], apply(wifi[4:9],2, A) )

#  X1 X2 X3 X4 X5 X6 X7 X8 X9
#1  1  1  1  2  2  2  2  2  2
#2  2  2  2  3  3  3  3  3  3
#3  3  3  3  4  4  4  4  4  4
#4  4  4  4  5  5  5  5  5  5

甚至:

data.frame(wifi[1:3], lapply(wifi[4:9], A) )
#or
cbind(wifi[1:3], lapply(wifi[4:9], A) )

#  X1 X2 X3 X4 X5 X6 X7 X8 X9
#1  1  1  1  2  2  2  2  2  2
#2  2  2  2  3  3  3  3  3  3
#3  3  3  3  4  4  4  4  4  4
#4  4  4  4  5  5  5  5  5  5

这篇关于R对特定数据框列的Apply()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆