R在使用if语句和for循环时生成错误

R在使用if语句和for循环时生成错误,r,if-statement,for-loop,R,If Statement,For Loop,下面是一个数据帧 brand production_cost sell A 220 3 B 180 1 C 200 2 D 240 4 E 270 7 F 200 4 如果sell>3则investment=sell*生产成

下面是一个数据帧

   brand  production_cost  sell
   A      220               3
   B      180               1
   C      200               2
   D      240               4
   E      270               7
   F      200               4
如果
sell>3
investment=sell*生产成本

如果
销售<3
,则
投资=销售*0.5*生产成本
(生产成本的50%)

我尝试过以下方法:

   data <- read.table("Z:\\who.txt",header=TRUE)

   investment <- c(1,1,1,1,1,1)

  for(i in 1:6){
    if(data$sell[i]>3){
      investment[i] <- sell[i] * production_cost
    }else {
      investment[i] <- sell[i] * 0.5 * production_cost
    }
  } # end for loop
  sum=0

  for(i in 1:6){
    if(produce[i]==1)sum=sum+1
  } # end for loop     
这里的问题是
投资[6]=800
。我试图将其标记为
1
。但它的标签是
0。

接下来,我必须找到
product=1
的品牌数量

我尝试了以下方法:

   data <- read.table("Z:\\who.txt",header=TRUE)

   investment <- c(1,1,1,1,1,1)

  for(i in 1:6){
    if(data$sell[i]>3){
      investment[i] <- sell[i] * production_cost
    }else {
      investment[i] <- sell[i] * 0.5 * production_cost
    }
  } # end for loop
  sum=0

  for(i in 1:6){
    if(produce[i]==1)sum=sum+1
  } # end for loop     

这个过程正确吗?还有更好的方法吗?

假设您的数据帧是
sample
。以下代码未经测试

#You can use `ifelse` for first two problem

 sample$investment<-with(sample, ifelse(sell>3,sell * production_cost,sell * 0.5 * production_cost))
 sample$produce<-with(sample,ifelse(investment>=800,1,0))

#subset the sample with produce equal to 1 for part 3 and then use ddply from plyr to #count the number of brands

samplesub<-subset(sample, produce==1)

#number of brands 

install.packages("plyr")
library(plyr)
num_brand<-ddply(samplesub, .(brand), summarize, freq=length(brand))

#Alternative to `ddply` from plyr package
#Rather than using the `plyr` package, you can use the following simple code for part 3
num_brand<-with(samplesub,table(brand))
#前两个问题可以使用'ifelse'
示例$investment3,销售*生产成本,销售*0.5*生产成本)
样本$PRODUCT=800,1,0)
#对于第3部分,使用等于1的农产品子集样本,然后使用plyr中的ddply来#计算品牌数量
samplesub在中使用,它创建一个环境并返回一个新的数据帧:

newdata = within(data, {
investment = ifelse(sell > 3, sell * production_cost, sell * production_cost *0.5 )
})

newdata = within(newdata, {
    produce = ifelse(investment >= 800, 1, 0)
})
注:此代码集

 investment = sell * production_cost * 0.5
如果销售=3


希望有帮助。

销售
生产成本
不存在,但
数据$sell
数据$production\u成本
存在。对dput(数据)进行后期处理,使其可重复。查看
?ifelse
提示:
内(数据,投资3,1,0.5))
鉴于此和您之前的问题,您可能希望从阅读开始,并从第6.3节关于数据帧的内容开始。plyr对于这个简单的任务来说开销太大。使用plyr对您的数据进行复杂处理。@Fernando:我会让OP来决定。为什么这里的
不起作用?有时
中的
expr
参数在没有大括号的情况下工作,有时则不工作。为什么?看到了吗?带着。基本上,with返回已计算的表达式,而in返回修改后的数据帧。