Renaming a column that R recognizes as a function [duplicate] - r

This question already has answers here:
How do I deal with special characters like \^$.?*|+()[{ in my regex?
(2 answers)
Closed 2 years ago.
I have a large data set with set column names, I need to rename the columns. Here are the columns:
class(spec_sub_act_feat_all)
[1] "data.frame"
names(spec_sub_act_feat_all[,82:86])
[1] "angle(tBodyAccMean,gravity)" "angle(tBodyAccJerkMean),gravityMean)"
[3] "angle(tBodyGyroMean,gravityMean)" "angle(tBodyGyroJerkMean,gravityMean)"
[5] "angle(X,gravityMean)"
class(names(spec_sub_act_feat_all[,82:88]))
[1] "character"
However, when I try to rename the columns using
names(spec_sub_act_feat_all) <- gsub(`angle(tBodyAccMean,gravity)`,
'Vector of mean body accelerometer signal',names(spec_sub_act_feat_all))
Error in gsub(`angle(tBodyAccMean,gravity)`, "Vector of mean body accelerometer signal", :
object 'angle(tBodyAccMean,gravity)' not found
or simply
names(spec_sub_act_feat_all[,82])<-"Vector of mean body accelerometer signal"
Neither one works. I believe my problem is that R is recognizing the column name as an actual function and won't let me select the character string to change it. The first renaming I tried with gsub(), I used `` to try to select the column name as not a function, which was recommended in another post, but did not work for me. I did notice that I could substitute out what was in the () but not the whole 'angle(...)' part.

As the ( and ) are metacharacters to capture the group in regex mode, if we use this in gsub, the default option is fixed = FALSE i.e. regex mode, either we need to escape (\\() or place it in square brackets ([(]) to literally evaluate it in regex mode or we can specify fixed = TRUE
gsub("angle(tBodyAccMean,gravity)",
'Vector of mean body accelerometer signal',
names(spec_sub_act_feat_all), fixed = TRUE)

Related

Why is there a space between strings when using the 'paste' function in R? I have used a separator [duplicate]

This question already has answers here:
What are the differences between "=" and "<-" assignment operators?
(9 answers)
What's the difference between `=` and `<-` in R? [duplicate]
(2 answers)
Closed 2 years ago.
When I input the following paste command:
rdsfile<-paste("Eobs","tmean","_81_10.rds",sep="")
I get: "Eobstmean_81_10.rds"
When I change the equals sign to the arrow usually used in R:
rdsfile<-paste("Eobs","tmean","_81_10.rds",sep<-"")
I get: "Eobs tmean _81_10.rds " (Note the space between "Eobs" and "tmean" and again between "tmean" and "_81_10.rds"
What is causing this to happen?
Parameters in functions should be assigned with an equals sign as in your first example so that you get your desired output.
What you are doing in your second example is to create a global object called sep with value "". You can easily check this by looking into your environment. Or simply type sep into the console.
But this global object sep is not used in the paste function, so the paste function falls back to its default, which is using a space (" ") as the separator.
Long story short: don't use <- for parameter assignments in functions.

Replace words that start with a period [duplicate]

This question already has answers here:
What special characters must be escaped in regular expressions?
(13 answers)
Closed 5 years ago.
I'm trying to fix a dataset that has some errors of decimal numbers wrongly typed. For example, some entries were typed as ".15" instead of "0.15". Currently this column is chr but later I need to convert it to numeric.
I'm trying to select all of those "words" that start with a period "." and replace the period with "0." but it seems that the "^" used to anchor the start of the string doesn't work nicely with the period.
I tried with:
dataIMN$precip <- str_replace (dataIMN$precip, "^.", "0.")
But it puts a 0 at the beginning of all the entries, including the ones that are correctly typed (those that don't start with a period).
If you need to do as you've stated, brackets [] are regex for 'find exact', or you can use '\\' which escapes a character, such as a period:
Option 1:
gsub("^[.]","0.",".54")
[1] "0.54"
Option 2:
gsub("^\\.","0.",".54")
[1] "0.54"
Otherwise, as.numeric should also take care of it automatically.

How to paste special characters in R [duplicate]

This question already has an answer here:
paste quotation marks into character string, within a loop
(1 answer)
Closed 5 years ago.
I have started learning R and am trying to create vector as below:
c(""check"")
I need the output as : "check". But am getting syntax error. How to escape the quotes while creating a vector?
As #juba mentioned, one way is directly escaping the quotes.
Another way is to use single quotes around your character expression that has double quotes in it.
> x <- 'say "Hello!"'
> x
[1] "say \"Hello!\""
> cat(x)
say "Hello!"
Other answers nicely show how to deal with double quotes in your character strings when you create a vector, which was indeed the last thing you asked in your question. But given that you also mentioned display and output, you might want to keep dQuote in mind. It's useful if you want to surround each element of a character vector with double quotes, particularly if you don't have a specific need or desire to store the quotes in the actual character vector itself.
# default is to use "fancy quotes"
text <- c("check")
message(dQuote(text))
## “check”
# switch to straight quotes by setting an option
options(useFancyQuotes = FALSE)
message(dQuote(text))
## "check"
# assign result to create a vector of quoted character strings
text.quoted <- dQuote(text)
message(text.quoted)
## "check"
For what it's worth, the sQuote function does the same thing with single quotes.
Use a backslash :
x <- "say \"Hello!\""
And you don't need to use c if you don't build a vector.
If you want to output quotes unescaped, you may need to use cat instead of print :
R> cat(x)
say "Hello!"

Using Gsub in R to remove a string containing brackets [duplicate]

This question already has answers here:
How do I deal with special characters like \^$.?*|+()[{ in my regex?
(2 answers)
Closed 6 years ago.
I'm trying to use gsub to remove certain parts of a string. However, I can't get it to work, and I think it's because the string to be removed contains brackets. Is there any way around this? Thanks for any help.
The command I want to use:
gsub('(4:4aCO)_','', '(5:3)_(4:4)_(5:3)_(4:4)_(4:4aCO)_(6:2)_(4:4a)')
Returns:
#"(5:3)_(4:4)_(5:3)_(4:4)_(4:4aCO)_(6:2)_(4:4a)"
Expected output:
#"(5:3)_(4:4)_(5:3)_(4:4)_(6:2)_(4:4a)"
A quick test to see if brackets were the problem:
gsub('te','', 'test')
#[1] "st"
gsub('(te)','', '(te)st')
#[1] "()st"
We can by placing the brackets inside the square brackets as () is a metacharacter
gsub('[(]4:4aCO[)]','', '(5:3)(4:4)(5:3)(4:4)(4:4aCO)(6:2)_(4:4a)')
Or with fixed = TRUE to evaluate the literal meaning of that character
gsub('(4:4aCO)','', '(5:3)(4:4)(5:3)(4:4)(4:4aCO)(6:2)_(4:4a)', fixed = TRUE)

Formatting R console output [duplicate]

This question already has answers here:
Remove quotes from a character vector in R
(11 answers)
Closed 6 years ago.
I would like to be able to copy and paste the output in R console without always having to remove these tags and quotes
print('love')
[1] "love"
What I require
print('love')
love
Note: I also want to remove the [1] not only the double quotes.
You could use the cat function, it will indeed print your string without parenthesis:
cat('love')
#### love
See the help page ?cat
Outputs the objects, concatenating the representations. cat performs
much less conversion than print.
You might also use print with the quote argument:
print("love", quote=FALSE)
#### [1] love
That way, you still get the [1]
See also this thread: https://stackoverflow.com/a/5218361/3871924

Resources