R 如何使用条件测试迭代地填充数据帧中的值
我正试图完成我最初认为是一项简单的任务,但我对R的编码技能显然非常生疏。简单地说,我在R“test”中设置了一个数据帧。X1是一个因子,X2是一个具有空值的列:R 如何使用条件测试迭代地填充数据帧中的值,r,loops,dataframe,data-entry,R,Loops,Dataframe,Data Entry,我正试图完成我最初认为是一项简单的任务,但我对R的编码技能显然非常生疏。简单地说,我在R“test”中设置了一个数据帧。X1是一个因子,X2是一个具有空值的列: X1-X2 F1 F1 F2 F3 F3 我使用这个程序的最终目标是创建一个函数或程序,该函数或程序将在因子的每个级别上进行迭代,要求用户提供一个值,用该值在当前级别的X1上填充X2,然后继续到下一级别的X1 你将如何编程 我的问题来自循环本身。要么循环没有重写X2的值(我假设它是一个局部变量),要么我得到了“condition h
- X1-X2
- F1
- F1
- F2
- F3
- F3
someValue<-0
for (i in levels(test$X1)){
if (identical(test$X1,i)) {
test$X2<-someValue}
someValue+1
}
#This doesn't seem to overwrite X2
someValue<-0
for (i in levels(test$X1)){
if (test$X1==i) {
test$X2<-someValue}
someValue+1
}
#This throws the 'condition has length >1' warning. I understand why this is happening.
However, ifelse isn't an option because I want it to do nothing
and iterate to the next level of i if false.
someValue此函数与您在问题中描述的相同:
fillfac <- function(vec){
fill <- character(length(vec))
# " iterate over each level of the factor"
for(i in levels(vec)){
#"ask the user for a value with which to fill X2"
# "over the current level of X1"
print(paste("What should be the fill for", i, "?"))
value <- scan(what = "character", n=1)
fill[labels(vec)[vec] == i] <- value
}
return(fill)
}
fillfac我想您需要的是ifelse
函数,而不是if
语句。@Dave2eifelse
需要一个“if false”条件。如果我在循环中迭代,并且迭代的每个级别都有一个唯一的值,那么“If false”参数需要使用什么?如果为true,则指定一个新值,如果为false,则继续使用现有值:test$X2
> X1 = factor(sample(1:5, size = 20, rep=T))
> X2 <- fillfac(X1)
[1] "What should be the fill for 1 ?"
1: "one"
Read 1 item
[1] "What should be the fill for 2 ?"
1: "two"
Read 1 item
[1] "What should be the fill for 3 ?"
1: "three"
Read 1 item
[1] "What should be the fill for 4 ?"
1: "four"
Read 1 item
[1] "What should be the fill for 5 ?"
1: "five"
Read 1 item
> (df <- as.data.frame(cbind(X1,X2)))
X1 X2
1 1 one
2 3 three
3 1 one
4 2 two
5 5 five
6 3 three
7 3 three
8 4 four
9 2 two
10 3 three
11 2 two
12 3 three
13 4 four
14 5 five
15 2 two
16 1 one
17 2 two
18 2 two
19 5 five
20 4 four