如何在 R 中的 .csv 文件中减去 2 列?

问题描述

如何在 R 上传的 .csv 文件中减去 2 列?

我已使用读数命名新列

解决方法

由于您没有发布任何示例数据,我发布了一个基于 iris 内置数据集的示例:您可以简单地使用 - 减去相同长度的向量(如果长度不是同样较短的向量将被回收)。 您可以使用 $ 运算符或 [] 运算符

从数据集中选择列
data(iris)
#assigning the result to a new column 
iris$subtraction <- iris$Sepal.Length-iris$Sepal.Width
iris$subtraction <- iris[,1]-iris[,2]

#assigning the result to a new variable
subtraction <- iris[,2]
subtraction <- iris$Sepal.Length-iris$Sepal.Width

编辑

mincrobenchmark 的 3 个等效解决方案:

library(microbenchmark)
library(data.table)
library(dplyr)
library(ggplot2)

#prepare simulation ------------------------------------------------------------

#number of rows to be tested
nr <- seq(100000,10000000,100000)

#initialize an list to store results
time <- as.list(rep(NA,100))

#benchmark
for (i in 1:length(nr)) {
  set.seed(5)
  #create data
  df <- data.frame(x=rnorm(nr[i]),y=rnorm(nr[i]))
  dt <- data.table(x=rnorm(nr[i]),y=rnorm(nr[i]))
  
  #benchmark
  x <- print(microbenchmark(
    base=df$new.col <- df$x-df$y,DT=dt <- dt[,new.col:=x-y],dplyr=df %>% mutate(new.col=x-y),times = 10
  ))
  #store results
  time[[i]] <- x[,c(1,4)]
}

#discard the first 4 elements because they run in microsenconds 
bench <- do.call(rbind,time[5:100])
#add the number of rows as column 
bench$nrow <- rep(nr[5:100],each=3)
ggplot(bench,aes(x=nrow,y=mean,group=expr,col=expr))+
  geom_smooth(se=F)+
  theme_minimal()+
  xlab("# rows")+
  ylab("time (milliseconds)")

enter image description here

如您所见,对于这个简单的任务,basedata.table 解决方案是等效的,而 mutate 解决方案要慢一些。然而,整个模拟在一分钟内运行,单个操作在几毫秒内运行。 我的 PC 有 16Gb RAM 和 12 个内核。

编辑

在 OP 要求一个 Date 案例之后,这里有一个日期为 POSIXct 类的小例子:

day <- Sys.Date()
hm <- merge(0:23,seq(0,45,by = 15))
datetime <- merge(last7days,chron(time = paste(hm$x,':',hm$y,0)))
colnames(datetime) <- c('date','time')

# create datetime
dt <- as.POSIXct(paste(datetime$date,datetime$time))

df <- data.frame(x=sample(dt,200000,replace = T),y=sample(dt,replace = T))
microbenchmark(df$x-df$y)

操作在几毫秒内运行,正如预期的那样:

Unit: milliseconds
        expr      min       lq     mean   median       uq     max neval
 df$x - df$y 1.459801 1.544301 2.755227 1.624501 1.845401 62.7416   100