0

I have a dataframe:

  smoke <- matrix(c(51,43,22,92,28,21,68,22,9),ncol=3,byrow=TRUE)
  colnames(smoke) <- c("High","Low","Middle")
  smoke=as.data.frame(smoke);smoke$sit[1]="bit"; smoke$sit[2]="bsa"
  smoke$sit[3]="bu"
    smoke
      High Low Middle sit
   1   51  43     22 bit
   2   92  28     21 bsa
   3   68  22      9  bu

I want apply my simple function:

    myf<- function(c,r){
    x=5*c+r
    write.table(x,paste0("res_", r, "_", c, ".txt"))}
    res=apply(smoke[,c('Low','High')], 1, function(x) myf(x[1],x[2]))

This works fine.output res_51_43.txt .......

Now I just want to add the corresponding names from smoke$sit to output text files. desired output res_bit_51_43.txt .......

    myf<- function(t,c,r){x=5*c+r
    write.table(x,paste0("res_", t, r, "_", c, ".txt"))}
   res=apply(smoke[,c('Low','High','sit')], 1, function(x) myf(x[1],x[2],x[3]))

I got this error:

              Error in 5 * c : non-numeric argument to binary operator
2
  • 1
    apply converts your data to matrix, and hence your variables to character (as matrices can only hold one data-type). And you would help yourself if you used more descriptive variable names in your function argument. Commented Nov 27, 2015 at 16:44
  • You could use lapply on a split dataframe (list can have multiple data-types in them) Commented Nov 27, 2015 at 17:10

1 Answer 1

1

Here's an example using lapply and split. Note: I've modified your function to return a filename.

myf<- function(c,r,t){
  x=5*c+r
  myfile <- paste0("res_", t, r, "_", c, ".txt")
  return(myfile)
}

res=lapply(split(smoke[,c('Low','High','sit')],1:nrow(smoke)), 
    FUN=function(x) myf(c=x[1],r=x[2],t=x[3]))
> res
$`1`
[1] "res_bit51_43.txt"

$`2`
[1] "res_bsa92_28.txt"

$`3`
[1] "res_bu68_22.txt"
Sign up to request clarification or add additional context in comments.

3 Comments

I'm not generating text files on my machine. What about the provided code is giving you problems?
Yes It worked but in the output text file, it does not return 'x(the name I provided)'. 'my function: "x" "Low" 266'______'yourfunction :"Low" "1" 266'
I couldn't really figure out your variable mappings, as you switch them around a lot. The issue of generating filenames and the error you got using 'apply' seems solved to me. Maybe try myf(c=x[2], r=x[1], t=x[3]) inside function(x)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.