问题
I have a problem with the f statement, because it's returning to me this error message : "the condition has length > 1 and only the first element will be used" I have a dataframe called data.summary, and I want to create two new variable vol.up and vol.down depending on the other variable of my dataframe. This is my script code :
data.summary <- call.dat12[,c("Dur...ms.", "Handset.Manufacturer",
"Src.Dst.Sig.Vol..Bytes.", "Dst.Src.Sig.Vol..Bytes.",
"group", "Src.Node.Type", "Dst.Node.Type")]
if (data.summary$Src.Node.Type == "eNodeB"){
data.summary$vol.up <- data.summary$Src.Dst.Sig.Vol..Bytes.
data.summary$vol.down <- data.summary$Dst.Src.Sig.Vol..Bytes.
} else {
data.summary$vol.up <- data.summary$Dst.Src.Sig.Vol..Bytes.
data.summary$vol.down <- data.summary$Src.Dst.Sig.Vol..Bytes.
}
I don't really inderstand why f statement doesn't work for vector ? Thank in advance
回答1:
Your comparison is a TRUE/FALSE vector with more than one element, for the if
- else
to work it is usually necessary a length-one logical vector that is not NA
. Maybe what you need is to vectorize the conditions:
ind <- data.summary$Src.Node.Type == "eNodeB"
data.summary$vol.up<- NA
data.summary$vol.down<- NA
#for true
data.summary$vol.up[ind]<- data.summary$Src.Dst.Sig.Vol..Bytes.[ind]
data.summary$vol.down[ind] <- data.summary$Dst.Src.Sig.Vol..Bytes.[ind]
data.summary
# for false
data.summary$vol.up[!ind]<- data.summary$Dst.Src.Sig.Vol..Bytes.[!ind]
data.summary$vol.down[!ind] <- data.summary$Src.Dst.Sig.Vol..Bytes.[!ind]
data.summary
来源:https://stackoverflow.com/questions/26934710/the-condition-has-length-1-and-only-the-first-element-will-be-used-error