String as input variable - R - arrays

I try to figure out how to solve this problem. I want to store different elements into an array such as xtrain1, xtrain2... xtrainN by using the paste() and seq() method. Also these elements represents a variable, which should be applied to the array function. The idea is to create a string of these elements and parse it to the array function, which recognized that this string are variables inside the function. Creating the vector seq_Xtrain it creates the elements for a desired number of logValues (e.g. 10) in a string. If I apply the different elements directly to the array function it works. I think the extraction of the elements inside the string does not work. Would be nice if someone can help me, thanks!
seq_Xtrain <- paste("xtrain", seq(from=1, to=logValue),sep="", collapse=", ")
### Output of seq_Xtrain
[1] "xtrain1, xtrain2, xtrain3, xtrain4, xtrain5, xtrain6, xtrain7, xtrain8, xtrain9, xtrain10"
x_train <<- array( c(seq_Xtrain), dim=c(dim(xtrain1),logValue))
####### For example this works
##x_train <<- array( c(xtrain1, xtrain2, xtrain3, xtrain4,xtrain5, xtrain6,
## xtrain7, xtrain8,xtrain9, xtrain10, xtrain11, xtrain12,
## xtrain13, xtrain14, xtrain15, xtrain16,xtrain17, xtrain18, xtrain19, xtrain20), dim=c(dim(xtrain1),20))
### Received output
> x_train[2]
[1] "xtest1, xtest2, xtest3, xtest4, xtest5, xtest6, xtest7, xtest8, xtest9, xtest10, xtest11, xtest12, xtest13, xtest14, xtest15, xtest16, xtest17, xtest18, xtest19, xtest20"
### Desired Output
> x_train[2]
[1] 0.4444944

I am not 100% sure what you want to do also because some reproducible sample data is missing. But look at this example where I use get:
logValue <- log(1:3)
xtrain1 <- log(1)
xtrain2 <- log(2)
xtrain3 <- log(3)
seq_Xtrain <- paste0("xtrain", 1:length(logValue))
x_train <- array(sapply(seq_Xtrain, get))
Get looks for objects of the desired name and retrieves their value. In this case this yields
> x_train
[1] 0.0000000 0.6931472 1.0986123

Related

Generating Image From Cell Array Using Imagesc Matlab

I have a cell array (3 x 4), called output, containing a 1024 x 1024 matrix in each cell. I want to plot the 4 matrices in ouput{1,:}. Furthermore, I have a structure, called dinfo, which correspondingly contains the names of each matrix (field with matrix names = "name"). I want each image to be titled with its name. Here is the code I have written thus far:
for i = 1:length(output{1,:})
figure
imagesc(output{1,i});
colormap('jet')
colorbar;
title(num2str(dinfo.name(i)))
end
I keep getting the error that "length has too many input arguments". If I change the code to avoid the length function-related error:
for i = 1:4
figure
imagesc(output{1,i});
colormap('jet')
colorbar;
title(num2str(dinfo.name(i)))
end
I get the error, "Expected one output from a curly brace or dot indexing expression, but there were 4 results".
Any thoughts on how I could resolve both of these errors?
Thank you for your time :)
output{1,:} is a comma-separated list; it contains the 1024 matrices of the first row of output, so length has 1024 arguments. The best way to obtain the number of columns is using size(...,2):
for i = 1:size(output,2)
figure
imagesc(output{1,i});
colormap('jet')
colorbar;
end
As for the second error, there is something wrong with dinfo.name; probably, it is also a comma-separated list because dinfo is a structure array. Try using dinfo(i).name instead of dinfo.name(i).

looping cor.test on split data

My small challenge is in the code of a loop I am trying to make of a dataframe that is split to allow correlations for each group
an example of what I need to achieve for each spp
rbt<-subset(Trjan,Trjan$Spp=="Redbilled Teal")
cotest<-cor.test(rbt$year,rbt$abundance)
vals<-c(cotest$estimate,cotest$p.value)
vals# at the end of the day I need a dataframe with species, slope & p value e.g. "Redbilled Teal" "its slope" "p value"
But because I have many spp I cant do this for all of them.After following some examples I got this code but I am failing to put my variables well.
uniq <- unique(unlist(Trjan$Spp))
for (i in 1:length(uniq)){
data_1 <- subset(Trjan, Spp == uniq[i])
cor.test(year,abundance)
vals<-c(estimate,p.value)
}
# error "abundance not found
any help. I thought my small problem would not need a sample of data, if need arise I can edit.
I finally got help from a friend, I realised that I needed to create a new empty data frame to store all my cor.test results by species
final.tab<-data.frame(Species=character(),cor_est=numeric(),cor_pval=numeric(),stringsAsFactors = F)
uniq <- unique(unlist(Trjan$Spp))
for (i in 1:length(uniq)){
data_1 <- subset(Trjan, Spp == uniq[i])
#I had to create an object to store your cor.test results and add the object name (i.e. "data_1$" before your column name)
cor.test.temp<-cor.test(data_1$year,data_1$abundance)
vals<-c(as.character(uniq[i]),round(as.numeric(cor.test.temp$estimate),3),round(as.numeric(cor.test.temp$p.value),3))
#progressively filling in my data.frame with cor.test results
final.tab[i,]<-vals
}

R script - nchar(x) function is not working in sapply

when I try to apply an sapply funcion to a data.frame, it does not work and I get this error:
"Error in nchar(x) : 'nchar()' requires a character vector"
the sapply funcion is:
as.data.frame(sapply(df,function(x) nchar(x)))
my test.data frame is:
df<-data.frame(valor1=c("R$ 27.144,22"," 30.035,07 "," 30.761,40 "),valor2=c("17.935,85","13.741,63","19.090,80"),valor3=c("0,00","0,00","1"))
I dont understand why I get that error because I've propperly formated my data frame as follows
df <- as.data.frame(sapply(df,as.character))
what I would want as a result would be a new data.frame were each element is the number of characters of each element in the older data.frame. In my test data.frame example, that would be:
valor1 valor2 valor3
[1]12 9 4
[2]11 9 4
[3]11 9 1
Well the answer lies in the error warning. nchar requires a character vector, which sapply will not provide here (When debugged, the output of sapply is "factor" not "character"). You have to use apply instead:
ncharsap <- function() {
df1 <-data.frame(valor1=c("R$ 27.144,22"," 30.035,07 "," 30.761,40 "),valor2=c("17.935,85","13.741,63","19.090,80"),valor3=c("0,00","0,00","1"))
df1 <- as.data.frame(sapply(df1,as.character))
df2 <- t(as.data.frame(apply(df1,1, function(x) nchar(x))))
return(df2)
}
Note: It is not good practice to use built-in function names for naming custom objects. So I changed df to df1. And also the output requires transpose by t to confirm with your required output.

Finding specific values in an array

I am relatively new to R programming. I am writing a code that generates an array of numbers:
[1] 0.5077399, 0.4388107, 0.3858783, 0.3462711, 0.3170844, 0.2954411, 0.2789464, 0.2658839,
[9] 0.2551246, 0.2459498
Note: I manually separated the values by commas for ease on the eyes :)
I want to pick the first 3 numbers from this array that are below 0.3 - [0.2954411, 0.2658839, 0.2551246]. In addition to picking these values, I want to generate the numbers that represents where those three values exist within the array. In this case, I want the code to give me [6,7,8].
How would I write code to do this?
I greatly appreciate the help.
For a similar simulated set,
y <- c(2, 4,6, 8)
ind <- which(y < 6) ## for finding indices 1 and 2
val <- y[y<6] ## for picking values 2 and 4

2d array in Haskell

I'm learning how to use arrays in Haskell, for example, generating a times table:
Prelude Data.Array> array ((0,0),(10,12)) [((x,y),x*y) | x<-[0..10], y<-[0..12]]
array ((0,0),(10,12)) [((0,0),0),((0,1),0),((0,2),0),((0,3),0),((0,4),0),((0,5),0),((0,6),0),((0,7),0),((0,8),0),((0,9),0),((0,10),0),((0,11),0),((0,12),0),((1,0),0),((1,1),1),((1,2),2),((1,3),3),((1,4),4),((1,5),5),((1,6),6),((1,7),7),((1,8),8),((1,9),9),((1,10),10),((1,11),11),((1,12),12),((2,0),0),((2,1),2),((2,2),4),((2,3),6),((2,4),8),((2,5),10),((2,6),12),((2,7),14),((2,8),16),((2,9),18),((2,10),20),((2,11),22),((2,12),24),((3,0),0),((3,1),3),((3,2),6),((3,3),9),((3,4),12),((3,5),15),((3,6),18),((3,7),21),((3,8),24),((3,9),27),((3,10),30),((3,11),33),((3,12),36),((4,0),0),((4,1),4),((4,2),8),((4,3),12),((4,4),16),((4,5),20),((4,6),24),((4,7),28),((4,8),32),((4,9),36),((4,10),40),((4,11),44),((4,12),48),((5,0),0),((5,1),5),((5,2),10),((5,3),15),((5,4),20),((5,5),25),((5,6),30),((5,7),35),((5,8),40),((5,9),45),((5,10),50),((5,11),55),((5,12),60),((6,0),0),((6,1),6),((6,2),12),((6,3),18),((6,4),24),((6,5),30),((6,6),36),((6,7),42),((6,8),48),((6,9),54),((6,10),60),((6,11),66),((6,12),72),((7,0),0),((7,1),7),((7,2),14),((7,3),21),((7,4),28),((7,5),35),((7,6),42),((7,7),49),((7,8),56),((7,9),63),((7,10),70),((7,11),77),((7,12),84),((8,0),0),((8,1),8),((8,2),16),((8,3),24),((8,4),32),((8,5),40),((8,6),48),((8,7),56),((8,8),64),((8,9),72),((8,10),80),((8,11),88),((8,12),96),((9,0),0),((9,1),9),((9,2),18),((9,3),27),((9,4),36),((9,5),45),((9,6),54),((9,7),63),((9,8),72),((9,9),81),((9,10),90),((9,11),99),((9,12),108),((10,0),0),((10,1),10),((10,2),20),((10,3),30),((10,4),40),((10,5),50),((10,6),60),((10,7),70),((10,8),80),((10,9),90),((10,10),100),((10,11),110),((10,12),120)]
I'm wondering if this is the correct way to hold a matrix or 2d-array of values? Why does it give a list of ((x,y),value) instead of giving a table of values? Is there a way to change how it prints the array?
Using a tuple as the index is the correct way of getting a multidimensional array. If you want to print it out differently, you'll have to write your own function to convert it to a string.
For example, you could have something like this:
showTable arr =
unlines $ map (unwords . map (show . (arr !))) indices
where indices = [[(x, y) | x <- [startX..endX]] | y <- [startY..endY]]
((startX, startY), (endX, endY)) = bounds arr
That's just the Show instance. The Array constructor is not exported from Data.Array, so you can't directly construct an array. The Show instance produces valid Haskell code that can be used to construct the array from the list of its associations.

Resources