我试图在R预先指定的数据框架Cars93中找到后轮驱动车价格的平均价格。这是我试过的......我出错了意外。
library(MASS) # has Cars93 data
rearcar <- c()
for(train in 1:nrow(Cars93)){
if(Cars93$DriveTrain[train] == Rear){
rearcar <- c(rearcar, train)
}
}
rearcarprice <- c()
for (train in rearcar){
rearcarprice <- c(rearcarprice, Cars93[train,6])
}
mean(rearcarprice)
答案 0 :(得分:2)
你根本不应该使用for循环。
这为数据的子集提供了&#34;后&#34;传动系:
Cars93[Cars93$DriveTrain == "Rear", ]
这是&#34; Price&#34;该数据子集的列:
Cars93[Cars93$DriveTrain == "Rear", "Price"]
因此,这是该子集的平均价格:
mean(Cars93[Cars93$DriveTrain == "Rear", "Price"])
# 28.95
您需要的只是最后一行代码。
答案 1 :(得分:1)
尝试纠正不匹配的花括号作为起点。并确保将Rear
放在引号中。
library(MASS)
rearcar<-c()
for(train in 1:nrow(Cars93))
{
if(Cars93$DriveTrain[train] == 'Rear'){
rearcar <- c(rearcar, train)
}
}
rearcarprice <- c()
for (train in rearcar) {
rearcarprice <- c(rearcarprice, Cars93[train,6])
}
mean(rearcarprice)
答案 2 :(得分:0)
看起来你在第一个for循环中有一个向后设置的括号。
当前
int[] ia = {99, 11, 7, 21, 4, 2};
System.arraycopy(
Arrays.stream(ia).
boxed().
sorted((a, b) -> b.compareTo(a)). // sort descending
mapToInt(i -> i).
toArray(),
0,
ia,
0,
ia.length
);
尝试:
for(train in 1:nrow(Cars93))
}
if(Cars93$DriveTrain[train] == Rear){
rearcar <- c(rearcar, train)
}}