Error when creating data frame with conditional branch on R

Asked 2 years ago, Updated 2 years ago, 36 views

kin<-c (-3,5,7,-6)
kin1<-kin[0<=kin]#0 or higher
kin2<-kin[0>kin]#0 or less

y<-c (1, 2, 3, 4)

kihon<-data.frame(y)#Creating Data Frames

Calculate positive and negative by conditional branch

 for (in 1:length(kin){
 if(kin1){
  pu<-data.frame(kin1*10)# plus calculation
  colnames(pu)<-c("point")#Change Point Name
 }
 if(kin2){
  mi<-data.frame(kin2*30)#Minus Calculation
  colnames(pu)<-c("point")#Change Point Name
 }
}

pumi<-rbind(pu,mi)#Connect positive and negative data
mydata<-data.frame(y,pumi)# data frame complete

If you write the code like this,

There are 50 or more warnings (use warning() to see the first 50)

A red message similar to the one above appears.

Also, mydata data frames are calculated in a different way by dividing the minus and plus of pumi, and then re-collecting them in the same column again, so they are not arranged in 1,2,3,4 like y data.

How do I deal with data frames and red messages above?

r

2022-09-30 19:43

1 Answers

Is this what you want to do?

kin<-c (-3,5,7,-6)
y<-c (1, 2, 3, 4)

kihon<-data.frame(y,point=NA)# data frame creation

# Calculate positive and negative as conditional branches
for (in 1:length(kin)) {
  if(kin[i]>=0){
    kihon[i, "point"]<-kin[i]*10#Change Point Name
  }
  if(kin[i]<0){
    kihon[i, "point"]<-kin[i]*30#Change Point Name
  }
}

kihon# data frame complete

For your information, I think the following methods are simpler and easier to understand.

kin<-c (-3,5,7,-6)
kihon<-data.frame(kin,point=ifelse(kin>=0,kin*10,kin*30))
kihon


2022-09-30 19:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.