我知道有其他的例子,但老实说,他们都不能回答我的问题,这就是为什么我要张贴这个。我有这个数据集,我想根据变量(列)来划分这个数据集。以下是dataset链接:https://drive.google.com/file/d/0B4Mldbnr1-avMDIxYmZLSnRfUDA/view?usp=sharing
以下是我迄今所做的工作:
# Reading data set
power <- read.csv("data set 6.csv", na.strings="",stringsAsFactors = FALSE)
# SUBSETTING
Area <- as.numeric(power$Area)
City <- as.factor(power$City)
P.Winter <- as.numeric(power$P.Winter)
P.Summer <- as.numeric(power$P.Summer)
#Part 1 - Data Cleaning and Transformation
str(power)
which(power$City == "Ackland ")
which(power$City == "Auckland ")
power$City[power$City == "Ackland "] <- "Auckland"
power$City <- trimws(power$City) # remove white spaces from all of them
power <- power[!(power$City =="Sydney"), ] # removing rows that contain "Sydney"
power <- power[!(power$Area =="-25"), ] # clear negative area
power <- power[!(power$P.Winter =="18000"), ]
#Adding new variable and calculates average power consumption
power$P.Annual <- as.numeric(power$P.Winter + power$P.Summer)/2
#To split dataset into two parts based on "City"
library(data.table)
Auckland <- data.table(power, power$City)
Auckland[, plot(P.Winter,P.Summer, P.Annual), by = list(City)]但是,这段代码会导致一个错误,而不是我所期望的那样:
输出:
Auckland <- data.table(power, power$City)
> Auckland[, plot("Auckland"), by = list(City)]
Error in plot.window(...) : need finite 'ylim' values
In addition: Warning messages:
1: In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by coercion
2: In min(x) : no non-missing arguments to min; returning Inf
3: In max(x) : no non-missing arguments to max; returning -Inf谢谢你的帮助
发布于 2017-11-09 02:00:11
如果我正确地理解了您的问题,您只需使用拆分函数,它就会将您的data.frame划分为一个基于城市的列表:
#To split dataset into two parts based on "City"
library(data.table)
splittedPower <- split(power, power$City)
str(splittedPower$Auckland)产出如下:
'data.frame': 248 obs. of 5 variables:
$ Area : num 144 177 269 209 124 ...
$ City : chr "Auckland" "Auckland" "Auckland" "Auckland" ...
$ P.Winter: num 1685 1927 2027 1938 1580 ...
$ P.Summer: num 1194 1487 1737 -158 1148 ...
$ P.Annual: num 1440 1707 1882 890 1364 ...https://stackoverflow.com/questions/47191820
复制相似问题