我一直在努力解决以下问题:
我有以下变量:
class(HARdata)
[1] "data.frame"
dim(HARdata)
[1] 10299 88
class(activity_labels)
[1] "character"
length(activity_labels)
[1] 6
我一直试图运行以下循环:
for (i in 1:nrow(HARdata)) {
for (j in 1:length(activity_labels)){
if (as.numeric(HARdata[i, "traintype"]) == extract_numeric(activity_labels[j])) {
HARdata[i, "traintype"] <- activity_labels[j]
}
}
}
但是,我收到以下错误:
Error in if (as.numeric(HARdata[i, "traintype"]) == extract_numeric(activity_labels[j])) { :
missing value where TRUE/FALSE needed
另外:警告信息: 强制引入的NA
如果我替换HARdata[i, "traintype"] <- activity_labels[j] with HARdata[i, "traintype"] <- 10
,代码运行正常。所以我认为问题出在这一行。左侧是数字,而右侧是字符。我试过运行as.character(HARdata[i, "traintype"]) <- "test"
,但这不起作用。任何人都可以看到可能出现的问题吗?
答案 0 :(得分:0)
test <- scan()
0.27513126 0.39694439
0.54228045 0.82751195
0.18600784 0.96602747
0.55259276 0.52368149
0.28976503 0.74500213
0.17534195 0.04931733
0.08077429 0.82169260
0.72602526 0.94921645
0.65077605 0.06989442
0.81399236 0.1379080
test <- as.data.frame(matrix(test, ncol=2))
names(test) <- c('cartype', 'traintype')
library(tidyr)
activity_labels <- c("$0.08077429", "$0.65077605")
test[,"traintype"][match(extract_numeric(activity_labels), test[,"traintype"])] <- activity_labels