[英]Iterate over the rownames of a column in r
I want to create a function that, given a string, iterates over the rownames of a dataframe, and, in case they´re equal, stores its value.我想创建一个 function,给定一个字符串,迭代 dataframe 的行名,如果它们相等,则存储它的值。 Here I give a toy example:
在这里我举一个玩具例子:
Places x1 x2 x3 x4 x5
A 0 5 0 0 0
B 0 0 0 23 0
C 23 0 0 0 0
D 8 0 0 0 0
I would like something like this:我想要这样的东西:
sequence <- ("ACF")
function(sequence)
>> 0 5 0 0 0 23 0 0 0 0
"A" is in the rownames of the dataframe, and so is "C", so the function stock their values in a new vector. “A”在 dataframe 的行名中,“C”也是如此,因此 function 将它们的值存储在一个新向量中。
codification <- function(sequence) {
bits <- vector()
for (i in sequence){
if (any(rownames(dataframe)==i)){
bits <- bits.append()
}
}
}
I think the rest of the function is working, but I couldnt find anything to write in bits <- bits.append()
to storage the values.我认为 function 的 rest 正在工作,但我找不到任何可以写入
bits <- bits.append()
来存储值的东西。 Any help would be really appreciated.任何帮助将非常感激。
You dont need a for loop.你不需要 for 循环。 Just some base R.
只是一些基地 R。
df <- read.table(text = "Places x1 x2 x3 x4 x5
A 0 5 0 0 0
B 0 0 0 23 0
C 23 0 0 0 0
D 8 0 0 0 0", header = TRUE)
codification <- function(sequence){
unlist(asplit(df[na.omit(match(strsplit(sequence, "")[[1]], df$Places)), -1], 1), use.names = FALSE)
}
codification("ACF")
#> [1] 0 5 0 0 0 23 0 0 0 0
codification("AACF")
#> [1] 0 5 0 0 0 0 5 0 0 0 23 0 0 0 0
Created on 2020-10-24 by the reprex package (v0.3.0)由reprex package (v0.3.0) 创建于 2020-10-24
However, if those are actually the row names, then you need this:但是,如果这些实际上是行名,那么您需要:
df <- read.table(text = " x1 x2 x3 x4 x5
A 0 5 0 0 0
B 0 0 0 23 0
C 23 0 0 0 0
D 8 0 0 0 0", header = TRUE)
codification <- function(sequence){
sequence <- strsplit(sequence, "")[[1]]
sequence <- sequence[sequence %in% rownames(df)]
unlist(asplit(df[sequence, ], 1), use.names = FALSE)
}
codification("ACF")
#> [1] 0 5 0 0 0 23 0 0 0 0
codification("AACF")
#> [1] 0 5 0 0 0 0 5 0 0 0 23 0 0 0 0
Created on 2020-10-24 by the reprex package (v0.3.0)由reprex package (v0.3.0) 创建于 2020-10-24
I would anyway suggest you to create a function that takes df as input.无论如何,我建议您创建一个将 df 作为输入的 function。
codification <- function(sequence, df){
# ...
}
It is not really good to use external objects inside a function.在 function 内部使用外部对象并不是很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.