0

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.

Roy_Batty
  • 135
  • 1
  • 2
  • 12
  • Are you sure that "A","B","C",etc are rownames in your data and not just another column? Normally rownames don't have a header. It's easier if you include a simple data in a [reproducible format](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) like `dput()` to clear up any confusion about how your data is stored. – MrFlick Oct 24 '20 at 00:15

1 Answers1

1

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.

Edo
  • 7,567
  • 2
  • 9
  • 19