![](/img/trans.png)
[英]How to replace values in multiple columns in a data.frame with values from a vector in R?
[英]R: Removing multiple columns from data frame based on vector values
我有一個數據框dataGL_all:
Date<-c("01-01-15 04:00","01-01-15 04:20","01-01-15 04:40")
FLIin<-c(96,39,72)
FLIout<-c(173,147,103)
FBEin<-c(96,116,166)
FBEout<-c(32,53,120)
dataGL_all<-data.frame(Date, FLIin, FLIout, FBEin, FBEout)
此外,我有一個矢量:
Remove <- c("FBEin", "FLIout")
我想要一段代碼來刪除向量中的列從數據框中刪除dataGL_all。 我已經嘗試了很多函數組合(例如grep(),c()和names())但是無法讓它工作...會很感激幫助:) thx
PS我的“真實”數據框包含68列,我想刪除36列(向量中的那些)。
dataGL_all[, !names(dataGL_all) %in% Remove]
應該做的伎倆。 或者,如果你想要grep
:
dataGL_all[, grep(paste(Remove, collapse = "|"), names(dataGL_all), invert = T)]
只是為了添加更多的可能性,使用data.table
包這些操作非常簡單。 您可以使用臨時刪除列!
和with = FALSE
組合。 或者您可以在data.table
環境中使用()
評估此向量時通過引用修改數據集,並使用:=
賦值運算符data.table
賦值NULL
,所以這里:
加載包並轉換為data.table
類
library(data.table)
setDT(dataGL_all)
然后要么做
dataGL_all[, !Remove, with = FALSE]
# Date FLIin FBEout
# 1: 01-01-15 04:00 96 32
# 2: 01-01-15 04:20 39 53
# 3: 01-01-15 04:40 72 120
或者通過引用更新數據集
dataGL_all[, (Remove) := NULL][]
# Date FLIin FBEout
# 1: 01-01-15 04:00 96 32
# 2: 01-01-15 04:20 39 53
# 3: 01-01-15 04:40 72 120
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.