Suppose I have the dataframe below:
>colnames(df)
>[1] "0939.HK.Open" "0939.HK.High" "0939.HK.Low" "0939.HK.Close" "0939.HK.Volume" "0939.HK.Adjusted"
Wondering if I can replace column name with a defined symbol?
>symbol<-'0123.KI'
And what I would like to obtain is:
>[1] "0123.KI.Open" "0123.KI.High" "0123.KI.Low" "0123.KI.Close" "0123.KI.Volume" "0123.KI.Adjusted"
Thank you so much guys.
Try:
colnames(df) <- paste0(symbol, ".", tools::file_ext(colnames(df)))
As the column names look like a filename, I am taking the extension - file_ext, then adding the symbol using paste0.
Another way:
symbol <- '0123.KI'
colnames(df) <- gsub("0939.HK", symbol, colnames(df), fixed=TRUE)
Related
the df column names are for instance:
split_the_tree1.zip.name, split_the_tree2.zip.region, split_the_tree3.zip.type
I would like to remove everything that comes before '.zip.' including the '.zip.'
To end up with column names: name, region, type
I tried something like this:
gsub(".*\zip\/", "", colnames(df))
gsub('*.zip', '', colnames(df))
colnames(df) <- gsub('.*zip.', '', colnames(df))
Note that we have .* and not *.
Although the quick way to do this is to note that the names you want are simply stored as extensions, hence use tools::file_ext function
strings <- c("split_the_tree1.zip.name", "split_the_tree2.zip.region",
"split_the_tree3.zip.type")
tools::file_ext(strings)
[1] "name" "region" "type"
I have a list
temp_list <- c("Temp01_T1", "Temp03_T1", "Temp04_T1", "Temp11_T6",
"Temp121_T6", "Temp99_T8")
I want to change this list as follows
output_list <- c("T1_Temp01", "T1_Temp03", "T1_Temp04", "T6_Temp11",
"T6_Temp121", "T8_Temp99")
Any leads would be appreciated
Base R answer using sub -
sub('(\\w+)_(\\w+)', '\\2_\\1', temp_list)
#[1] "T1_Temp01" "T1_Temp03" "T1_Temp04" "T6_Temp11" "T6_Temp121" "T8_Temp99"
You can capture the data in two capture groups, one before underscore and another one after the underscore and reverse them using backreference.
This should work.
sub("(.*)(_)(.*)", "\\3\\2\\1", temp_list)
You capture the three groups, one before the underscore, one is the underscore and one after and then you rearrange the order in the replacement expression.
python approach: splitting on '_', reversing order with -1 step index slicing, and joining with '_':
['_'.join(i.split('_')[::-1]) for i in temp_list]
You can use str_split() from stringr and then use sapply() to paste it in the order you want if it is always seperated by a _
x <- stringr::str_split(temp_list, "_")
sapply(x, function(x){paste(x[[2]],x[[1]],sep = "_")})
A trick with paste + read.table
> do.call(paste, c(rev(read.table(text = temp_list, sep = "_")), sep = "_"))
[1] "T1_Temp01" "T1_Temp03" "T1_Temp04" "T6_Temp11" "T6_Temp121"
[6] "T8_Temp99"
I have a df with 3 columns. The second column contains directory paths. How do I separate the first level directory of the path and create a new column for it?
The df looks like this:
file_path file_name
/owner1/project1/third name1.bam
/owner2/project2/hard/fourth name2.bam
/owner2/project3/easy/ name3.bam
/owner3/project4/A. name4.bam
The output I seek is:
owner. file_path. file_name. f
/owner1 /project1/third. name1.bam
/owner2 /project2/hard/fourth. name2.bam
/owner2. /project3/easy. name3.bam
/owner3. /project4/A. name4.bam
I have tried "mutate", but when I use the "/" as the separator, it splits all the levels. All I want is to separate the first level of the path. Is there another approach or function that can accomplish this?
It's unclear to me what you're looking to do precisely but you may want to try using strsplit(x, split = "/") and then index the output.
Edit:
Hey Lou_A, maybe the follwing is what you are looking. There are probably more elegant ways of doing this but this is what came to mind.
df <- data.frame(lvl = c("levela1/levela2/levela3",
"levelb1/levelb2/levelb3",
"levelc1/levelc2/levelc3"))
df[,"lvl1"] <- sapply(strsplit(df[,1], "/"), `[`, 1)
rep.fun <- function(str){
lvl1 = strsplit(str, "/")[[1]][1]
low.lvl = gsub(lvl1, "", str)
return(low.lvl)
}
df[,"rest.lvl"] <- sapply(df[,1], rep.fun)
library(stringr)
df <- data.frame(lvl = c("levela1/levela2/levela3",
"levelb1/levelb2/levelb3",
"levelc1/levelc2/levelc3"))
df <- cbind(str_split_fixed(df$lvl, '/', n=2), df[,-1])
I have a name vector like the following:
vname<-c("T.Lovullo (73-58)","K.Gibson (63-96) and A.Trammell (1-2)","T.La Russa (81-81)","C.Dressen (16-10), B.Swift (32-25) and F.Skaff (40-39)")
Watch out for T.La Russa who has a space in his name
I want to use str_match to separate the name. The difficulty here is that some characters contain two names while the other contain only one like the example I gave.
I have write my code but it does not work:
str_match_all(ss,"(D[.]D+.+)s(\\(d+-d+\\))(s(and)s(D[.]D+.+)s(\\(d+-d+\\)))?")
Perhaps this helps
res <- unlist(strsplit(vname, "(?<=\\))(\\sand\\b\\s)*", perl = TRUE))
res
#[1] "T.Lovullo (73-58)" "K.Gibson (63-96)" "A.Trammell (1-2)" "T.La Russa (81-81)"
To get the names only (if that is what the expected)
sub("\\s*\\(.*", "", res)
#[1] "T.Lovullo" "K.Gibson" "A.Trammell" "T.La Russa"
I am using R to do some data pre-processing, and here is the problem that I am faced with: I input the data using read.csv(filename,header=TRUE), and then the space in variable names became ".", for example, a variable named Full Code became Full.Code in the generated dataframe. After the processing, I use write.xlsx(filename) to export the results, while the variable names are changed. How to address this problem?
Besides, in the output .xlsx file, the first column become indices(i.e., 1 to N), which is not what I am expecting.
If your set check.names=FALSE in read.csv when you read the data in then the names will not be changed and you will not need to edit them before writing the data back out. This of course means that you would need quote the column names (back quotes in some cases) or refer to the columns by location rather than name while editing.
To get spaces back in the names, do this (right before you export - R does let you have spaces in variable names, but it's a pain):
# A simple regular expression to replace dots with spaces
# This might have unintended consequences, so be sure to check the results
names(yourdata) <- gsub(x = names(yourdata),
pattern = "\\.",
replacement = " ")
To drop the first-column index, just add row.names = FALSE to your write.xlsx(). That's a common argument for functions that write out data in tabular format (write.csv() has it, too).
Here's a function (sorry, I know it could be refactored) that makes nice column names even if there are multiple consecutive dots and trailing dots:
makeColNamesUserFriendly <- function(ds) {
# FIXME: Repetitive.
# Convert any number of consecutive dots to a single space.
names(ds) <- gsub(x = names(ds),
pattern = "(\\.)+",
replacement = " ")
# Drop the trailing spaces.
names(ds) <- gsub(x = names(ds),
pattern = "( )+$",
replacement = "")
ds
}
Example usage:
ds <- makeColNamesUserFriendly(ds)
Just to add to the answers already provided, here is another way of replacing the “.” or any other kind of punctation in column names by using a regex with the stringr package in the way like:
require(“stringr”)
colnames(data) <- str_replace_all(colnames(data), "[:punct:]", " ")
For example try:
data <- data.frame(variable.x = 1:10, variable.y = 21:30, variable.z = "const")
colnames(data) <- str_replace_all(colnames(data), "[:punct:]", " ")
and
colnames(data)
will give you
[1] "variable x" "variable y" "variable z"