r - 如何在 R 中减去 .csv 文件中的 2 列?
问题描述
如何在 R 中上传的 .csv 文件中减去 2 colmun?
我已使用读取命名新列 <- $started_time- $ended_time
解决方案
由于您没有发布任何示例数据,我发布了一个基于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
编辑
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)")
如您所见,对于这个简单的任务,thebase
和data.table
solutions 是等价的,而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
推荐阅读
- http - 接收方是否可以减少 HTTP/2 流控制窗口?
- sql - 如何使用 ODBC 包从 R 更改 SQL 表的变量类型?
- networking - 电路交换与虚电路交换
- python - 字符串的 Numba 矢量化:NotImplementedError:unicode_type 不能表示为 Numpy dtype
- java - Java中的默认超类
- javascript - 如何使用 mysql 模块在没有 ORM 的情况下访问 Nodejs 类中的数据库实例
- javascript - 调整足球间距以填充屏幕 - React/CSS
- coq - 如何在 Coq 中对重复的假设进行分组?
- mongodb - MongoDb/NextJs:帮助使用它的 id 更新和删除我的数据库中的特定数组
- codeigniter-4 - 过滤器在 Codeiginter 4 中不起作用