从数据集创建两个数据集以便再次重用

时间:2017-11-09 00:04:04

标签: r split dataset subset

我知道还有其他的例子,但说实话,他们没有人能回答我的问题,这就是我发布这个问题的原因。 我有这个数据集,我想根据变量(列)划分这个数据集。 这是数据集链接: 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

感谢您的帮助 感谢

1 个答案:

答案 0 :(得分:2)

如果我正确理解您的问题,您只需要使用拆分功能,它会将您的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 ...