在列表中执行ifelse():将符号*替换为0、.替换为1
Hey there! I see you need to replace the * and . symbols in your data structure using R's ifelse() function. Let's walk through how to do this properly.
Solution for Replacing Symbols with
ifelse() First, let's clarify: the structure you provided is actually a data frame (not a simple list) in R. Here's how you can use ifelse() to swap * for 0 and . for 1, while keeping other values (like "4", "5", "a") unchanged:
Step 1: Assign your data to a variable
First, let's make sure we have your data stored properly:
# Store your original data frame my_df <- structure( list( `1` = c("4", "*", ".", ".", "*", ".", ".", "*", "*", ".", "*", ".", ".", ".", ".", ".", "."), `2` = c("5", ".", ".", ".", ".", ".", "*", ".", ".", ".", "*", ".", ".", ".", ".", "*", ".", "*", ".", ".", "*", "*", "*", "*", "*", "."), `3` = c("4", ".", ".", ".", ".", "*", ".", ".", "*", ".", ".", "a", "*", ".", "*", ".", ".") ), .Names = c("1", "2", "3") )
Step 2: Use lapply() + ifelse() to process each column
We'll loop through every column in the data frame, and apply ifelse() to replace the symbols:
# Process each column with nested ifelse() processed_df <- as.data.frame( lapply(my_df, function(column) { # First replace * with 0, then . with 1, keep others as-is ifelse(column == "*", 0, ifelse(column == ".", 1, column)) }) )
Step 3: Check the result
If you print processed_df, you'll see all * are now 0, all . are 1, and values like "4", "5", "a" stay the same.
How this works:
lapply(my_df, function(column): This iterates over each column in your data frame, passing one column at a time to the function.- Nested
ifelse(): We first check if the value is*—if yes, replace with 0. If not, check if it's.—replace with 1. Any other value is left unchanged. as.data.frame(): Converts the list output fromlapply()back into a data frame (sincelapply()returns a list by default).
内容的提问来源于stack exchange,提问作者user8248672
相关产品推荐
相关产品推荐

