Filling matrix with array coordinates in R - r

I am trying to fill a matrix so that each element will be a string consisting of its coordinates (row, column).
i.e.
[ '1,1' '1,2' '1,3' ]
[ '2,1' '2,2' '2,3' ]
[ '3,1' '3,2' '3,3' ]
I have been able to do this with a square matrix but it is not robust if I vary the number of rows or columns.
This is what I have so far
#Works but only with a square matrix
x <- 20 #Number of rows
y <- 20 #Number of columns
samp <- 200 #Number of frames to sample
grid = matrix(data = NA,nrow = x,ncol = y)
for (iter_col in 1:y){
for (iter_row in 1:x){
grid[iter_col,iter_row] = paste(toString(iter_row),toString(iter_col),sep = ',')
}
}
I am using this to randomly sample a grid which I superimpose on images for a cell counting method. So I do not have any data yet. Not all of these grids will have equal numbers of rows and columns.
Can you help me make this more flexible? My background in R is a little lacking so the solution my be right in front of me...
Thanks!
Edit
My variables in grid[iter_col,iter_row] were in the wrong order. Once they were switched it works for matrices of varying dimensions.
Thanks G5W for catching that error.

Here's one way using sapply
rows = 4
columns = 5
sapply(1:columns, function(i) sapply(1:rows, function(j) paste(j,i,sep = ", ")))
# [,1] [,2] [,3] [,4] [,5]
#[1,] "1, 1" "1, 2" "1, 3" "1, 4" "1, 5"
#[2,] "2, 1" "2, 2" "2, 3" "2, 4" "2, 5"
#[3,] "3, 1" "3, 2" "3, 3" "3, 4" "3, 5"
#[4,] "4, 1" "4, 2" "4, 3" "4, 4" "4, 5"

I suspect this would be much faster:
matrix(paste0(rep(seq_len(x), times=y), ", ", rep(seq_len(y), each=x)), nrow = x, ncol = y)
[,1] [,2] [,3] [,4] [,5]
[1,] "1, 1" "1, 2" "1, 3" "1, 4" "1, 5"
[2,] "2, 1" "2, 2" "2, 3" "2, 4" "2, 5"
[3,] "3, 1" "3, 2" "3, 3" "3, 4" "3, 5"
[4,] "4, 1" "4, 2" "4, 3" "4, 4" "4, 5"
OR using col and row (as mentioned in the comments by #rawr)
grid[] <- paste0(row(grid), ", ", col(grid))

Related

expand numbers with text separated by hyphen R

Following the question here
How to expand a given range of numbers to include all numbers separated by a dash
It worked well with "text+ number range", like in the example "Ballroom 1-3"
The code is this
expand.dash <- function(dashed) {
limits <- as.numeric(unlist(strsplit(dashed, '-')))
seq(limits[1], limits[2])
}
expand.ballrooms <- function(txt) {
str <- gsub('\\d+\\s?-\\s?\\d+', '%d', txt)
dashed_str <- gsub('[a-zA-Z ]+', '', txt)
sprintf(str, expand.dash(dashed_str))
}
>expand.ballrooms("Ballroom 1-3")
#[1] "Ballroom 1" "Ballroom 2" "Ballroom 3"
>expand.ballrooms("Ballroom 1 - 3")
#[1] "Ballroom 1" "Ballroom 2" "Ballroom 3"
But if there is "text+number - text+number", for example "Ballroom1 - Ballroom3"
The original code doesn't work well, and returns
[1] "Ballroom1 - Ballroom3" "Ballroom1 - Ballroom3" "Ballroom1 - Ballroom3"
And I reckon would need to change this line
str <- gsub('\\d+-\\d+', '%d', txt)
But I can't really figure out how it could work.
The result should still be "Ballroom 1" "Ballroom 2" "Ballroom 3".
Thank you!
Here is a base R way.
x <- "Ballroom1 - Ballroom3"
y <- gsub("[^[:digit:]\\-]", "", x)
expand.ballrooms(paste("Ballrooms", y))
#[1] "Ballrooms 1" "Ballrooms 2" "Ballrooms 3"
This should cover just about everything:
expand.ballroom <- function(x) {
m <- str_match( x, "Ballroom *(\\d+) *- *(?:Ballroom)? *(\\d+)" )
return( paste( "Ballroom", m[,2]:m[,3] ) )
}
expand.ballroom( "Ballroom1 - Ballroom3" )
expand.ballroom( "Ballroom 1 - Ballroom 3" )
expand.ballroom( "Ballroom 1-3" )
expand.ballroom( "Ballroom1-3" )
expand.ballroom( "Ballroom 1 - 3" )
It produces:
> expand.ballroom( "Ballroom1 - Ballroom3" )
[1] "Ballroom 1" "Ballroom 2" "Ballroom 3"
> expand.ballroom( "Ballroom 1 - Ballroom 3" )
[1] "Ballroom 1" "Ballroom 2" "Ballroom 3"
> expand.ballroom( "Ballroom 1-3" )
[1] "Ballroom 1" "Ballroom 2" "Ballroom 3"
> expand.ballroom( "Ballroom1-3" )
[1] "Ballroom 1" "Ballroom 2" "Ballroom 3"
> expand.ballroom( "Ballroom 1 - 3" )
[1] "Ballroom 1" "Ballroom 2" "Ballroom 3"
This will extract the first word, e.g. Ballroom from the string, and the digits.
expand.dash <- function(dashed) {
limits <- as.numeric(unlist(strsplit(dashed, '-')))
seq(limits[1], limits[2])
}
expand.ballrooms <- function(txt) {
str <- paste0(gsub("([A-Za-z]+).*", "\\1", txt), "%d")
dashed_str <- gsub('[a-zA-Z ]+', '', txt)
sprintf(str, expand.dash(dashed_str))
}
> expand.ballrooms("Ballroom 1-3")
[1] "Ballroom1" "Ballroom2" "Ballroom3"
> expand.ballrooms("Ballroom 1 - 3")
[1] "Ballroom1" "Ballroom2" "Ballroom3"
> expand.ballrooms("Ballroom1 - Ballroom3")
[1] "Ballroom1" "Ballroom2" "Ballroom3"
Base R solution:
test1 <- "Ballroom 1 - 3"
test2 <- "Ballroom1 - Ballroom3"
expand.ballrooms <- function(string_to_expand){
y <- unlist(strsplit(string_to_expand, "\\s*\\-\\s*"))
prefix <- Filter(function(z){z!=""}, trimws(gsub("(\\d+)|\\-", "", y)))
nos <- trimws(gsub("\\D+", "", y))
res <- paste(prefix, eval(parse(text=paste0(nos, collapse = ":"))))
return(res)
}
expand.ballrooms(test1)
expand.ballrooms(test2)

string manipulation in matrix in R

I have a matrix like so
A = matrix(
c("2 (1-3)", "4 (2-6)", "3 (2-4)", "1 (0.5-1.5)", "5 (2.5-7.5)", "7 (5-9)"),
nrow=3,
ncol=2)
I want to replace all strings where the first element is less than 5 (ie "0" or "1" or "2" or "3" or "4") with "< 5". It should be:
B = matrix(
c("< 5", "< 5", "< 5", "< 5", "5 (2.5-7.5)", "7 (5-9)"),
nrow=3,
ncol=2)
Any ideas?
Extract the 1st number, convert it into numeric and replace the numbers which are less than 5 with "<5".
A[as.numeric(sub('(\\d+).*', '\\1', A)) < 5] <- '< 5'
A
# [,1] [,2]
#[1,] "< 5" "< 5"
#[2,] "< 5" "5 (2.5-7.5)"
#[3,] "< 5" "7 (5-9)"
A shortcut to extract the first number and to convert it to numeric is using readr::parse_number.
A[readr::parse_number(A) < 5] <- '< 5'
Use substr() to etract the 1st chcaracter of each matrix element. As long as that is a number you can convert it to one via as.numeric()
A[as.numeric(substr(A,1,1))<5] <- "<5"
We don't need to extract and convert to numeric if there are only 5 options:
ie "0" or "1" or "2" or "3" or "4"
A[grep("^[0-4]", A)] <- "< 5"
Or
replace(A, grep("^[0-4]", A), "< 5")
Or
replace(A, startsWith("[0-4]", A), "< 5")
Result
# [,1] [,2]
# [1,] "< 5" "< 5"
# [2,] "< 5" "5 (2.5-7.5)"
# [3,] "< 5" "7 (5-9)"
1) read.table
Use read.table to get the first number in each cell giving vector firstNo. Then use replace to replace those cells with < 5.
The original input A is preserved which is generally desirable to make it easier to test and debug but if you prefer to overwrite it anyways then replace the left hand side of the second line of code with A.
No regular expressions and no packages are used.
firstNo <- read.table(text = A)[[1]]
B <- replace(A, firstNo < 5, "< 5")
B
giving:
[,1] [,2]
[1,] "< 5" "< 5"
[2,] "< 5" "5 (2.5-7.5)"
[3,] "< 5" "7 (5-9)"
Although not needed for the sample input in the question, if it is possible that the text after the left parenthesis is irregular then you might need to add the fill=TRUE or comment.char = "(" arguments to read.table.
2) gsubfn
gsubfn is like gsub except it inputs the capture groups in the regular expression, i.e. the parenthesized portions of the regular expression, into the function expressed in formula notation in the second argument and then replaces the match with the output of the function.
library(gsubfn)
B <- replace(A,
TRUE,
gsubfn("^(\\d) (.*)", ~ if (as.numeric(x) < 5) "< 5" else paste(x, y), A)
)
B
giving:
[,1] [,2]
[1,] "< 5" "< 5"
[2,] "< 5" "5 (2.5-7.5)"
[3,] "< 5" "7 (5-9)"

How to order an array of character according to the numbers that it contains

I would like to order the following vector of chr:
x=c("class 1", "class 2", "class 4", "class 7", "class 5", "class 3", "class 6",
"class 10", "class 9", "class 11", "class 8", "class 12", "class 21")
according to the numbers that appear in the characters. E.g., in this case, the desired result is:
class 1, class 2, class 3, class 4, class 5, class 6, class 7, class 8, class 9, class 10, class 11
class 12, class 21
I tried with:
x[order(x)]
but obtaining a different result:
> x[order(x)]
[1] "class 1" "class 10" "class 11" "class 12" "class 2" "class 21" "class 3"
[8] "class 4" "class 5" "class 6" "class 7" "class 8" "class 9"
As mentioned, it is sorting alphabetically, and not considering the numeric value contained within the string.
There are a number of options to address this:
library(stringr)
str_sort(x, numeric = TRUE)
[1] "class 1" "class 2" "class 3" "class 4" "class 5" "class 6" "class 7" "class 8" "class 9" "class 10" "class 11" "class 12" "class 21"
Or
library(gtools)
mixedsort(x)
[1] "class 1" "class 2" "class 3" "class 4" "class 5" "class 6" "class 7" "class 8" "class 9" "class 10" "class 11" "class 12" "class 21"
Or without using another package, strip away "class" and use the numeric result to sort:
values <- as.numeric(gsub("class", "", x))
x[order(values)]
[1] "class 1" "class 2" "class 3" "class 4" "class 5" "class 6" "class 7" "class 8" "class 9" "class 10" "class 11" "class 12" "class 21"
That's because x is a vector of class "character" and elements (strings) are ordered alphabetically. Extract number from the strings an convert them to numeric type
y <- as.integer(substr(x, 7,8))
# y has the same order that x
# sort integers (numeric order) and match positions of unordered intergers
# match returns indexes of y ordered by sort(y)
x[match(y, sort(y))]
# Output is:
# [1] "class 1" "class 2" "class 7" "class 6" "class 5" "class 4" "class 3" "class 11" "class 9" "class 8" "class 10" "class 12"
# [13] "class 21"

Combining levels from 3 to 1 (basic)

I have a data column called "Health" with the following four levels: "0 0", "0 1", "1 0" and "1 1"
How do I create a new column where I:
combine the three levels "0 1", "1 0" and "1 1" and rename it as "1"
rename the fourth level "0 0" as "0"
Thank you

Merge two lists into single list containing single character vectors R

Okay I'm stumped, I know there are answers about merging lists, and my attempt builds on those answers, but they don't return a single char vector. I have a function that merges lists but the values are separate character vectors:
I dont want the characters as separate strings
csc.list <- mapply(c, rep("CSC", 16), c(1:16), SIMPLIFY=FALSE)
$CSC
[1] "CSC" "1"
$CSC
[1] "CSC" "2"
...
I don't know how to combine the characters in rows with a wierd heading
csc.list <- mapply(unlist, c(mapply(c, rep("CSC", 16), c(1:16), SIMPLIFY=FALSE)))
CSC CSC CSC CSC CSC ...
[1,] "CSC" "CSC" "CSC" "CSC" "CSC" ...
[2,] "1" "2" "3" "4" "5" ...
Desired Result of two merged lists
c("CSC 1", "CSC 2", "CSC 3", "CSC 4", "CSC 5", ... , "CSC 16")
[1] "CSC 1" "CSC 2" "CSC 3" "CSC 4" "CSC 5" ... "CSC 16"
Bonus if your answer scales to merging more than two, i.e. n lists into single vector of merged characters:
csc.list <- mapply(c, rep("CSC", 16), c(1:16), rep(".R", 16), SIMPLIFY=FALSE)
lalalala <- f(csc.list)
Desired result of three merged lists
[1] "CSC 1.R" "CSC 2.R" ...
(source: placekitten.com)
Are you looking for something like this?:
csc.list <- mapply(c, rep("CSC", 16), c(1:16), SIMPLIFY=FALSE)
#merge the list into a string
output<-sapply(csc.list, toString)
#remove the added commas
output<-gsub(",", "", output)
This question is 3 years old at the time of writing this. However, I am adding this answer as it might help some people. What you are looking for is the flatten_chr() function in the purrr package.
csc.list <- mapply(c, rep("CSC", 16), c(1:16), SIMPLIFY=FALSE)
library(purrr)
flatten_chr(csc.list)

Resources