【发布时间】:2014-06-11 03:53:20
【问题描述】:
我正在尝试将日期因子转换为可由 for 循环引用的字符向量。 for 循环应将数据框的“Day”列(例如,如下所示)中的 NA 值替换为与日期对应的值。
Date Time Axis1 Day Sum.A1.Daily
1 6/12/10 5:00:00 20 NA NA
2 6/12/10 5:01:00 40 NA NA
3 6/13/10 5:02:00 50 NA NA
4 6/13/10 5:03:00 10 NA NA
5 6/14/10 5:04:00 20 NA NA
6 6/14/10 5:05:00 30 NA NA
我需要把它改成这样:
Date Time Axis1 Day Sum.A1.Daily
1 6/12/10 5:00:00 20 1 60
2 6/12/10 5:01:00 40 1 60
3 6/13/10 5:02:00 50 2 80
4 6/13/10 5:03:00 30 2 80
5 6/14/10 5:04:00 20 3 50
6 6/14/10 5:05:00 30 3 50
使用我当前的代码,我得到的是:
Date Time Axis1 Day Sum.A1.Daily
1 6/12/10 5:00:00 20 NA 60
2 6/12/10 5:01:00 40 NA 60
3 6/13/10 5:02:00 50 NA 80
4 6/13/10 5:03:00 30 NA 80
5 6/14/10 5:04:00 20 NA 50
6 6/14/10 5:05:00 30 NA 50
将值分配给第 4 列的 for 循环出现问题。我需要帮助理解两件事:
- 问题是什么(下面的当前脚本)
- 如果我可以通过更有效地使用因子水平来规避问题
我是 R 和 stackoverflow 的新手——对这个社区的酷炫感到不知所措。如果我违反了基本的提问规则,请告诉我。
## read in file; define classes
## (important b/c I want R to utilize factor levels of "Date" in column 1 of .csv file)
dat <- read.csv("data.csv", header = T, ## read in file
colClasses = c("factor", "character", "integer", "integer", "integer"))
## assign values to be used by for loops
levs <- lapply(dat, levels) ## grab levels for factor variable of dates
dates <- c(levs$Date) ## creates list of dates to reference in for loop
counts <- c(1:length(dates)) ## creates vector 1:number of dates listed in file for loop 2
x <- (1:nrow(dat)) ## creates vector 1:number of rows in file
## for loop 1 will cycle through rows in file;
## for loop 2 cycle through values in "counts" variable
## if() compares value of each object in "Dates" (col. 1)
## to one of the value of one of the levels (e.g., compared to "6/22/10", not 1)
## if ==, assigns corresp. value of "counts" to the appropriate obs. of col. 4
("Day")
for (i in x) {
for (j in counts) {
if (dat[i,1] == levs[j]) {
dat[i,4] <- counts[j]
}
}
}
dat <- transform(dat, Sum.A1.Daily = ave(dat$Axis1, dat$Date, FUN = sum))
if(!file.exists("ActData.csv")) { ## Enter file name for new data
write.csv(dat, file = "ActData2.csv") ## Enter file name for new data
} else { stop("change file name")
}
print("File Cleaning Complete")
head(dat)
tail(dat)
【问题讨论】:
-
见
?cat-(Returned) Value: None。不要尝试将没有值的cat(...)分配给对象。 -
那我怎样才能将这组新的值赋给一个对象呢?
-
从我猜测的代码中删除
cat()。 -
为什么要加逗号?
-
因为这是我知道我的嵌套 for 循环(如当前编写的)将接受数据的唯一方法。我是一个极端的新手,我试图一次操纵一件事。
标签: r date for-loop vector r-factor