首页 > 解决方案 > 如何在 R 中减去 .csv 文件中的 2 列?

问题描述

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

我已使用读取命名新列 <- $started_time- $ended_time

标签: rsumsubtraction

解决方案


由于您没有发布任何示例数据,我发布了一个基于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[,1]-iris[,2]
subtraction <- iris$Sepal.Length-iris$Sepal.Width

编辑

mincrobenchmark3个等效解决方案中的一个:

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)")

在此处输入图像描述

如您所见,对于这个简单的任务,thebasedata.tablesolutions 是等价的,而mutate解决方案要慢一些。然而,整个模拟在一分钟内运行,单个操作在几毫秒内运行。我的电脑有 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,200000,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

推荐阅读