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.
我想学习如何在我的数据帧的特定列上应用函数,而不“排除”我的df中的其他列。例如,我想将一些特定列乘以1000,并保留其他列。
Using the sapply function for example like this:
使用sapply函数,例如:
a<-as.data.frame(sapply(table.xy[,1], function(x){x*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:
我得到了新的数据帧,第一列乘以1000,但没有我在操作中没有使用的其他列。所以我的尝试就是这样做:
a<-as.data.frame(sapply(table.xy, function(x) if (colnames=="columnA") {x/1000} else {x}))
but this one didn't work.
但是这个没用。
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?
我的解决方法是为两个数据帧提供另一行ID,然后将旧数据框与新创建的数据框合并以获得完整的数据帧。但我认为必须有更好的解决方案。不是吗?
2 个解决方案
#1
6
If you only want to do a computation on one or a few columns you can use transform
or simply do index it manually:
如果您只想对一列或几列进行计算,可以使用transform或者只需手动索引:
# 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
#2
0
The following code will apply the desired function to the only the columns you specify. I'll create a simple data frame as a reproducible example.
以下代码将所需的函数应用于您指定的列。我将创建一个简单的数据框作为可重现的示例。
(df <- data.frame(x = 1, y = 1:10, z=11:20))
(df <- cbind(df[1], apply(df[2:3],2, function(x){x*1000})))
Basically, use cbind()
to select the columns you don't want the function to run on, then use apply()
with desired functions on the target columns.
基本上,使用cbind()选择不希望函数运行的列,然后在目标列上使用带有所需函数的apply()。
#1
6
If you only want to do a computation on one or a few columns you can use transform
or simply do index it manually:
如果您只想对一列或几列进行计算,可以使用transform或者只需手动索引:
# 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
#2
0
The following code will apply the desired function to the only the columns you specify. I'll create a simple data frame as a reproducible example.
以下代码将所需的函数应用于您指定的列。我将创建一个简单的数据框作为可重现的示例。
(df <- data.frame(x = 1, y = 1:10, z=11:20))
(df <- cbind(df[1], apply(df[2:3],2, function(x){x*1000})))
Basically, use cbind()
to select the columns you don't want the function to run on, then use apply()
with desired functions on the target columns.
基本上,使用cbind()选择不希望函数运行的列,然后在目标列上使用带有所需函数的apply()。