使用条件句沿着数据框的列循环
Loop along a column of a dataframe with conditional sentence
我有以下数据集:
FO.1 Pilot T.O
VAM F
CAM F
LYA C
FRZ F
DYN F
VAM F
VAM C
CAM F
我想 运行 沿 FO#1
列和 Pilot T/O
列循环。循环需要识别每个 FO#1,如果 Pilot T/O 是 F 或 C。例如,如果 FO#1 是 VAF,结果应该显示 Pilot T/O 取值的次数F 或 C.
我试过以下方法:
#Loading the dataset
test2 <- read.xlsx(file = 'test.xlsx', 1)
#Count
count=0
#Loop across the elements of FO.1 column
for (i in test2$FO.1)
{
#Conditional sentence to check if the element takes the value F
if (test2$Pilot.T.O[i] == 'F')
{
#We add 1 to the count
count[i] <- count+1
}
}
但是,我收到以下错误消息:
Error in if (test2$Pilot.T.O[i] == "F") { :
missing value where TRUE/FALSE needed
这是一个基本的 R 解决方案:
- 解决方案 1:使用
sapply()
+table()
res <- sapply(c("C","F"), function(x) table(df)[,x])
这样
> res
C F
CAM 0 2
DYN 0 1
FRZ 0 1
LYA 1 0
VAM 1 2
或 res <- table(df)
> res
Pilot T.O
FO.1 C F
CAM 0 2
DYN 0 1
FRZ 0 1
LYA 1 0
VAM 1 2
- 解决方案 2:使用
split()
+ table()
res <- Map(table,split(df,df$FO.1))
这样
> res
$CAM
Pilot T.O
FO.1 F
CAM 2
$DYN
Pilot T.O
FO.1 F
DYN 1
$FRZ
Pilot T.O
FO.1 F
FRZ 1
$LYA
Pilot T.O
FO.1 C
LYA 1
$VAM
Pilot T.O
FO.1 C F
VAM 1 2
数据
df <- structure(list(FO.1 = c("VAM", "CAM", "LYA", "FRZ", "DYN", "VAM",
"VAM", "CAM"), `Pilot T.O` = c("F", "F", "C", "F", "F", "F",
"C", "F")), class = "data.frame", row.names = c(NA, -8L))
我有以下数据集:
FO.1 Pilot T.O
VAM F
CAM F
LYA C
FRZ F
DYN F
VAM F
VAM C
CAM F
我想 运行 沿 FO#1
列和 Pilot T/O
列循环。循环需要识别每个 FO#1,如果 Pilot T/O 是 F 或 C。例如,如果 FO#1 是 VAF,结果应该显示 Pilot T/O 取值的次数F 或 C.
我试过以下方法:
#Loading the dataset
test2 <- read.xlsx(file = 'test.xlsx', 1)
#Count
count=0
#Loop across the elements of FO.1 column
for (i in test2$FO.1)
{
#Conditional sentence to check if the element takes the value F
if (test2$Pilot.T.O[i] == 'F')
{
#We add 1 to the count
count[i] <- count+1
}
}
但是,我收到以下错误消息:
Error in if (test2$Pilot.T.O[i] == "F") { :
missing value where TRUE/FALSE needed
这是一个基本的 R 解决方案:
- 解决方案 1:使用
sapply()
+table()
res <- sapply(c("C","F"), function(x) table(df)[,x])
这样
> res
C F
CAM 0 2
DYN 0 1
FRZ 0 1
LYA 1 0
VAM 1 2
或 res <- table(df)
> res
Pilot T.O
FO.1 C F
CAM 0 2
DYN 0 1
FRZ 0 1
LYA 1 0
VAM 1 2
- 解决方案 2:使用
split()
+table()
res <- Map(table,split(df,df$FO.1))
这样
> res
$CAM
Pilot T.O
FO.1 F
CAM 2
$DYN
Pilot T.O
FO.1 F
DYN 1
$FRZ
Pilot T.O
FO.1 F
FRZ 1
$LYA
Pilot T.O
FO.1 C
LYA 1
$VAM
Pilot T.O
FO.1 C F
VAM 1 2
数据
df <- structure(list(FO.1 = c("VAM", "CAM", "LYA", "FRZ", "DYN", "VAM",
"VAM", "CAM"), `Pilot T.O` = c("F", "F", "C", "F", "F", "F",
"C", "F")), class = "data.frame", row.names = c(NA, -8L))