R:将功能应用于保留数据帧其余部分的特定列 [英] R: Apply function on specific columns preserving the rest of the dataframe

查看:110
本文介绍了R:将功能应用于保留数据帧其余部分的特定列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解如何在我的数据框的特定列上应用功能,而不会从我的df排除其他列。例如,我想将一些特定的列乘以1000,并保留其他列。

I'd like to learn how to apply functions on specific columns of my dataframe without "excluding" the other columns from my df. For example i'd like to multiply some specific columns by 1000 and leave the other ones as they are.

使用sapply函数,例如:

Using the sapply function for example like this:

    a<-as.data.frame(sapply(table.xy[,1], function(x){x*1000}))

我得到新的数据帧与第一列乘以1000,但没有其他列,我没有在操作中使用。所以我试图这样做:

I get new dataframes with the first column multiplied by 1000 but without the other columns that I didn't use in the operation. So my attempt was to do it like this:

    a<-as.data.frame(sapply(table.xy, function(x) if (colnames=="columnA") {x/1000} else {x}))

但这一个没有工作。

我的解决方法是给数据帧另一行带有ID,稍后将新数据帧与新创建的数据帧合并,以获得一个完整的数据帧。但我认为必须有一个更好的解决方案。不是吗

My workaround was to give both dataframes another row with IDs and later on merge the old dataframe with the newly created to get a complete one. But I think there must be a better solution. Isn't it?

推荐答案

如果您只想在一列或几列上进行计算,您可以使用 transform 或者只是手动进行索引:

If you only want to do a computation on one or a few columns you can use transform or simply do index it manually:

# with transfrom:
df <- data.frame(A = 1:10, B = 1:10)
df <- transform(df, A = A*1000)

# Manually:
df <- data.frame(A = 1:10, B = 1:10)
df$A <- df$A * 1000

这篇关于R:将功能应用于保留数据帧其余部分的特定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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