级别:[1,4,5] [1,5] [1] [2,4] [2] [3,5]
,但是每个级别中都有多个元素。那么如何从各个级别提取/访问元素/项目
sample<-read.csv(file.choose(), header=T)
df<-as.data.frame(sample)
df
v<-df$Nodes[]
w<-df$FirstDegree[]
for (i in v) {
t<-c(1:5)
if (df$FirstDegree[t][2]==i){
print(1)
}
else {
print(0)
}
}
答案 0 :(得分:0)
我将因子转换为字符对象,然后检查字符串中是否存在1到5度。
假设这是您的数据
FirstDegree <- factor(c("[1, 4, 5]", "[1,5]", "[1]", "[2, 4]", "[2]", "[3, 5]"))
FirstDegree
Levels: [1, 4, 5] [1,5] [1] [2, 4] [2] [3, 5]
我会
FirstDegree <- as.character(FirstDegree)
# sapply runs the code below for every possible degree 1 to 5
m <- sapply(1:5, function(degreenumber){
# we convert the number 1 to 5 to a character and see if this number
# is present in the vector FirstDegree. grepl returns TRUE or FALSE but since
# you asked for 1 or 0 we use as.numeric
as.numeric(grepl(as.character(degreenumber), FirstDegree))})
# the resulting matrix looks like this:
m
[,1] [,2] [,3] [,4] [,5]
[1,] 1 0 0 1 1
[2,] 1 0 0 0 1
[3,] 1 0 0 0 0
[4,] 0 1 0 1 0
[5,] 0 1 0 0 0
[6,] 0 0 1 0 1