简体   繁体   中英

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. 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.

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. Any help would be really appreciated.

You dont need a for loop. Just some base 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)


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)


I would anyway suggest you to create a function that takes df as input.

codification <- function(sequence, df){
  
  # ...

}

It is not really good to use external objects inside a function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM