R:创建一个对不同行进行操作的函数,并使用其值创建一个新列



我有以下数据帧(df1(。该数据帧包含一个称为";平均值";它具有每列的平均值。

GDP    per_capita 
France    2         5
Spain     4         10
Italy     6         15
Mean      4         10

我想创建一个函数,复制df1的列,每个新列的值是每个单元格减去其各自的平均值,再除以其平均值。像这样:

GDP    per_capita   GDP_diff   per_capita_diff
France    2         5        (2-4)/4      (5-10)/10
Spain     4         10       (4-4)/4      (10-10)/10
Italy     6         15       (6-4)/4      (15-10)/10
Mean      4         10       (4-4)/4      (10-10)/10

所以最后,它应该是这样的:

GDP    per_capita    GDP_diff   per_capita_diff
France   2        5         -0.5          -0.5
Spain    4        10            0           0
Italy    6        15         0.5           0.5
Mean     4        10           0            0

我必须假设将使用该函数的每个数据帧都有一个名为"的行;平均值";。到目前为止,这就是我所拥有的:

new.function <- function(df){
name.df= colnames(df)
new.df = apply(df, FUN = function(x) (x-Mean)/Mean, MARGIN = 2)
colnames(new.df) = paste(name.df,"diff",sep ="_")
result = cbind(df,new.df)
return(result)
}

然而,我得到的结果都是错误的。它不是像我希望的那样减法或除法。

您的问题是零件(x-Mean)/MeanMean在任何地方都不存在——你可能指的是mean(x)

new.function <- function(df){
name.df<- colnames(df)
new.df <- apply(df, MARGIN=2, FUN=function(x) (x-mean(x))/mean(x))
colnames(new.df) <- paste(name.df, "diff", sep ="_")
result <- cbind(df, new.df)
return(result)
}
new.function(df)
#        GDP per_capita GDP_diff per_capita_diff
# France   2          5     -0.5            -0.5
# Spain    4         10      0.0             0.0
# Italy    6         15      0.5             0.5
# Mean     4         10      0.0             0.0

数据:

df <- structure(list(GDP = c(2L, 4L, 6L, 4L), per_capita = c(5L, 10L, 
15L, 10L)), class = "data.frame", row.names = c("France", "Spain", 
"Italy", "Mean"))

数据表方法:

x <- data.frame(GDP = c(2,4,6), per_capita=c(5,10,15))
rownames(x) <- c("F", "ES", "IT")
library(data.table)
setDT(x)
x[,`:=`(GDP_diff = (GDP-mean(GDP, na.rm=T))/mean(GDP, na.rm=T),
per_capita_diff = (per_capita-mean(per_capita, na.rm=T))/mean(per_capita, na.rm=T))]

尝试使用dplyr中的mutate()来直接计算避免循环的变量:

library(dplyr)
library(tidyr)
#Code
new <- df %>%
mutate(GDP_diff=(GDP-mean(GDP))/mean(GDP),
per_capita_diff=(per_capita-mean(per_capita))/mean(per_capita))

输出:

GDP per_capita GDP_diff per_capita_diff
1   2          5     -0.5            -0.5
2   4         10      0.0             0.0
3   6         15      0.5             0.5
4   4         10      0.0             0.0

使用的一些数据:

#Data
df <- structure(list(GDP = c(2L, 4L, 6L, 4L), per_capita = c(5L, 10L, 
15L, 10L)), class = "data.frame", row.names = c("France", "Spain", 
"Italy", "Mean"))

最新更新